寄生组合式继承

寄生组合式继承(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']
相关推荐
摘星编程38 分钟前
用React Native开发OpenHarmony应用:StickyHeader粘性标题
javascript·react native·react.js
A_nanda42 分钟前
c# 用VUE+elmentPlus生成简单管理系统
javascript·vue.js·c#
天天进步20151 小时前
Motia事件驱动的内核:深入适配器(Adapter)层看消息队列的流转
javascript
北极糊的狐1 小时前
若依项目vue前端启动键入npm run dev 报错:不是内部或外部命令,也不是可运行的程序或批处理文件。
前端·javascript·vue.js
有诺千金2 小时前
VUE3入门很简单(4)---组件通信(props)
前端·javascript·vue.js
2501_944711432 小时前
Vue-路由懒加载与组件懒加载
前端·javascript·vue.js
●VON3 小时前
React Native for OpenHarmony:构建高性能、高体验的 TextInput 输入表单
javascript·学习·react native·react.js·von
●VON3 小时前
React Native for OpenHarmony:ActivityIndicator 动画实现详解
javascript·学习·react native·react.js·性能优化·openharmony
霍理迪3 小时前
JS其他常用内置对象
开发语言·前端·javascript
pusheng20254 小时前
普晟传感2026年新春年会总结与分析
前端·javascript·html