寄生组合式继承

寄生组合式继承(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']
相关推荐
FYKJ_201021 小时前
springboot大学校园论坛管理系统--附源码42669
java·javascript·spring boot·python·spark·django·php
Highcharts.js1 天前
数据之美:用Highcharts打造专业级弧线图
javascript·数据库·highcharts·图表开发·弧线图
SuperEugene1 天前
错误处理与 try/catch:真实项目里应该捕什么错?
前端·javascript·面试
夕除1 天前
js--22
前端·javascript·python
Qhappy1 天前
某加密企业版过frida检测
javascript
用户5757303346241 天前
🔥 一文搞懂 JavaScript 包装类(面试必考)
javascript
滕青山1 天前
Base64编码/解码 核心JS实现
前端·javascript·vue.js
sww_10261 天前
SAA ReactAgent工作原理
开发语言·前端·javascript
linux_cfan1 天前
拒绝“黑屏”与“哑剧”:Web视频播放器UX体验与自动播放选型指南 (2026版)
前端·javascript·音视频·html5·ux
be or not to be1 天前
假期js学习汇总
前端·javascript·学习