欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 资讯 > 寄生组合式继承

寄生组合式继承

2025/5/17 8:27:21 来源:https://blog.csdn.net/m0_46543935/article/details/140642868  浏览:    关键词:寄生组合式继承

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

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

定义父类和子类。
创建父类原型的一个副本,并将其赋值给子类的原型。
修正子类的构造函数指针。
给子类添加一个调用父类构造函数的函数,并传递相应的参数。

// 父类构造函数
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']

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词