寄生组合式继承

寄生组合式继承(Parasitic Combination Inheritance)是 JavaScript 中实现继承的一种方式,它结合了组合继承和寄生继承的优点,同时避免了组合继承中的性能问题。组合继承会导致父类构造函数被调用两次,而寄生组合式继承通过使用原型链来避免这一问题。

下面是寄生组合式继承的实现步骤:

定义父类和子类。

创建父类原型的一个副本,并将其赋值给子类的原型。

修正子类的构造函数指针。

给子类添加一个调用父类构造函数的函数,并传递相应的参数。

js 复制代码
// 父类构造函数
function Parent(name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];
}

Parent.prototype.sayName = function() {
  console.log(this.name);
};

// 子类构造函数
function Child(name, age) {
  Parent.call(this, name); // 继承实例属性,第一次调用 Parent 构造函数
  this.age = age;
}

// 创建父类原型的副本
function inheritPrototype(child, parent) {
  let prototype = Object.create(parent.prototype); // 创建对象
  prototype.constructor = child; // 增强对象
  child.prototype = prototype; // 赋值对象
}

// 继承父类的原型方法
inheritPrototype(Child, Parent);

Child.prototype.sayAge = function() {
  console.log(this.age);
};

// 测试代码
const child1 = new Child('Alice', 18);
child1.sayName(); // 输出: Alice
child1.sayAge(); // 输出: 18
child1.colors.push('black');
console.log(child1.colors); // 输出: ['red', 'blue', 'green', 'black']

const child2 = new Child('Bob', 20);
child2.sayName(); // 输出: Bob
child2.sayAge(); // 输出: 20
console.log(child2.colors); // 输出: ['red', 'blue', 'green']
相关推荐
ZC跨境爬虫19 分钟前
跟着 MDN 学 HTML day_12:(HTML网页图片嵌入)
前端·javascript·css·ui·html
是上好佳佳佳呀37 分钟前
【前端(十二)】JavaScript 函数与对象笔记
前端·javascript·笔记
Rkgua1 小时前
ESModule和Commonjs模块的区别
前端·javascript
江南十四行1 小时前
AI Agent应用类型及Function Calling开发实战(三)
服务器·前端·javascript
yqcoder1 小时前
JavaScript 数据类型全景图:从基础到进阶
开发语言·javascript·ecmascript
吴声子夜歌2 小时前
Vue3——脚手架Vite
前端·javascript·vue.js·vite
threelab2 小时前
Three.js 3D 饼图效果 | 三维可视化 / AI 提示词
javascript·人工智能·3d
傻瓜搬砖人3 小时前
SpringMVC的请求
java·前端·javascript·spring
木易 士心3 小时前
为什么 Promise 比 setTimeout 先执行?——JavaScript 事件循环与异步顺序完全指南
开发语言·javascript·ecmascript
爱上好庆祝3 小时前
学习js的第六天(js基础的结束)
开发语言·前端·javascript·学习·ecmascript