手写寄生组合继承
寄生组合继承的特点:
- 只调用一次父类构造函数
- Child 可以向 Parent 传参
- 父类方法可以复用
- 父类的引用属性不会被共享
function Parent (name) {
this.name = name;
this.say = () => {
console.log('我的名字是' + this.name);
};
}
Parent.prototype.play = () => {
console.log('打篮球');
};
function Child (name) {
Parent.call(this);
this.name = name;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
let child = new Child('张三');
child.say();
child.play();
console.log(child.name);
function inherit(child,parent){
// 获取父级共有属性
let prototype = createObject(parent.prototype);
// 父级共有属性 继承 给孩子
child.prototype = prototype;
// 孩子的 指向 自身
prototype.constructor = child;
}