js 继承
- ES5 继承
- 下图为比较难以理解的继承方法部分
<script>
//es5继承
//我们创建一个父函数person 让student函数来继承person
//创建 Person
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.hello = function () {
console.log('hello 继承');
}
//创建 Student 让他继承 Person
function Student(name, age, sid) {
//下面是继承属性的过程
//首先 name和age属性我希望可以通过Person继承得到
//我们可以通过函数的调用来实现Person的复用
// Person(name,age)
//但上面的写法,在Person中的this 就会指向 window 而window是没有这两个属性的
//所以我们可以强行改变Person函数中this的指向 可以通过 call apply bind方法中的随意一个
//这里我们用call call的用法为 call(要this指向的对象,参数1,参数2);
Person.call(this, name, age); //这里在this为 Student
this.sid = sid;
}
//下面是继承方法的过程
//首先我们知道Person的方法是存放在prototype上面的 那么我们要做的就是,将Student的prototype 指向Person的prototype就可以了
// Student.prototype=Person.prototype;
//但这种方式会出现一个问题,就是在给Student添加方法的话,就会直接添加到Person上
//所以我们可以创建一个空元素,让他的__proto__指向Person的prototype
let tmp = Object.create(Person.prototype);
// Object.create(对象A) 返回一个空对象 其__proto__指向对象A的prototype
//然后将 Student的prototype 指向空对象的__proto__
Student.prototype = tmp;
//如果子类的方法与父类方法同名,想要执行父类的方法,子类的方法要在继承之后写
Student.prototype.hello = function () {
console.log('hello 继承!!!')
}
let p = new Person('xiaoxiao', 6);
console.log(p.name, '-', p.age);
p.hello();
let s = new Student('xiaoming', 18, '1653');
console.log(s.name, '-', s.sid);
s.hello();
</script>
- ES6 继承
- Es6的继承在原理上与es5是一样的。
<script>
//Es6 继承
//es6的继承是通过extends实现的
//同样我们创建一个父函数Person,让Student来继承
//创建Person
class Person {
constructor(name, age) {
this.age = age;
this.name = name;
}
hello() {
console.log('hello world')
}
}
//创建 Student
class Student extends Person {
constructor(name, age, sid) {
//es6的属性与方法继承,通过super
super(name, age);
this.sid = sid;
}
//如果想执行student自己的hello方法
hello() {
console.log('hello node.js')
}
}
let p = new Person('xiaoxiao', 6);
console.log(p.name, '-', p.age);
p.hello();
let s = new Student('xiaoming', 18, '1653');
console.log(s.name, '-', s.sid);
s.hello();
</script>