继承
各种继承
-
原型链继承,把子类原型指向父类的一个实例,但是多个子类共享这个实例,如果实例上有引用类型会造成紊乱(联系到 vue 中 data 返回对象)
-
构造函数继承,在子类的构造函数中调用父类构造函数,从而可以传参数,但是只能继承构造器用到的属性不能继承自带属性
-
组合继承 = 原型链继承+构造函数继承,但因为用的是父类的实例,所以执行了两次父类构造函数,子类实例和原型上同时有 a 属性
-
寄生继承,把父类的原型拷贝,再把子类 原型指向拷贝
-
寄生组合式继承 = 寄生继承+构造函数继承(缺点?如果方法没写在父类原型而是写在父类上则继承不到?)
实现寄生组合式继承
function inheritPrototype(subClass, superClass) {
// 复制一份父类的原型
var tem = Object.create(superClass.prototype);
// 修正构造函数
tem.constructor = subClass;
// 设置子类原型
subClass.prototype = tem;
}
function Parent(name, id) {
this.id = id;
this.name = name;
this.list = ["a"];
this.printName = function () {
console.log(this.name);
};
}
Parent.prototype.sayName = function () {
console.log(this.name);
};
function Child(name, id) {
Parent.call(this, name, id); //***用子的参数,执行一遍父类的构造过程
//相当于执行了this.name =id
// this.name = name
// .....节省了写多行赋值的时间
// Parent.apply(this, arguments);
}
inheritPrototype(Child, Parent); //注意这里会覆盖Child的prototype
//所以对Child的prototype增加方法要放在这行语句后面,对parent的prototype增加方法要放在这行的前面
Chinese.prototype.getAge = function () {
return this.age;
};