// 寄生组合式继承,使用了构造函数 和 寄生式继承的方式
function parent(name){
this.name = name;
this.color = ['blue', 'red', 'grey'];
}
parent.prototype.getName = function(){
console.log('父类实例方法——', this.name);
}
function child(name, theme){
parent.call(this, name);
this.theme = theme;
}
// 相当于使用child 替换掉了 parent的位置
function initPrototype(child, parent){
let prototype = Object.create(parent.prototype); // 创建对象,拿到父类实例的原型对象
// 解绑原来的关系 绑定新关系
prototype.constructor = child;
child.prototype = prototype;
}
initPrototype(child, parent);
child.prototype.sayName = function(){
console.log('this.sayName', this.name);
}
let child1 = new child('123', 'color');
child1.sayName();
child1.getName();
前端手撕代码——寄生组合式继承.js
最新推荐文章于 2024-08-10 14:32:18 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)