寄生组合式继承

寄生组合式继承(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']
相关推荐
刘发财2 小时前
弃用html2pdf.js,这个html转pdf方案能力是它的几十倍
前端·javascript·github
ssshooter8 小时前
看完就懂 useSyncExternalStore
前端·javascript·react.js
Live0000010 小时前
在鸿蒙中使用 Repeat 渲染嵌套列表,修改内层列表的一个元素,页面不会更新
前端·javascript·react native
柳杉10 小时前
使用Ai从零开发智慧水利态势感知大屏(开源)
前端·javascript·数据可视化
球球pick小樱花10 小时前
游戏官网前端工具库:海内外案例解析
前端·javascript·css
喝水的长颈鹿10 小时前
【大白话前端 02】网页从解析到绘制的全流程
前端·javascript
用户145369814587810 小时前
VersionCheck.js - 让前端版本更新变得简单优雅
前端·javascript
codingWhat10 小时前
整理「祖传」代码,就是在开发脚手架?
前端·javascript·node.js
码路飞11 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
Lee川11 小时前
优雅进化的JavaScript:从ES6+新特性看现代前端开发范式
javascript·面试