前言
寄生式组合继承,目前相对来说,是最好的一种js继承方式,那我们就简单说说它是怎么实现继承的。
function Parent(name) {
this.name = name;
this.eat = () => {
console.log('吃什么');
};
}
Parent.prototype.look = () => {
console.log('看什么');
};
function Child(name) {
Parent.call(this);
this.name = name;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
// let newChild = new Child("DDD");
// console.log(newChild.name); // "DDD"
// newChild.eat(); // '吃什么'
// newChild.look(); // '看什么'
实现寄生组合式继承的方式
1-借助构造函数
Parent.call(this)
通过call,执行Parent构造函数,并且让执行构造函数的this指向Child。
所以使得Child拥有了Parent里面this.name = name和 this.eat = () => {}这些静态方法
2-借助原型链的形式继承
首先,Object.create(obj)的本质就是:
创建一个新对象,新对象的__proto__ = obj
所以,Child.prototype = Object.create(Parent.prototype)
,我们把Parent的原型拷贝了一份给Child的原型。相对于一个副本,实现了通过原型链,继承原型上的属性和方法
(创建一个副本的好处:Child.prototype
添加了属性和方法,也只会挂在这个副本的prototype
上,并不会影响到Parent的prototype)
之后通过Child.prototype.constructor = Child
; 为Child.prototype添加constructor,弥补因为重写原型而失去的constructor属性
寄生组合式继承的优点
可以继承父类原型对象和实例上的属性和方法,只需要调用一次父类构造函数,Child可以向Parent传参,父类方法可以复用
总结
寄生组合式继承通过构造函数来继承静态属性,通过创建副本的方式来继承原型链上的属性