文章目录
在JavaScript的继承机制中,寄生组合继承(Parasitic Combination Inheritance)是一种被广泛推荐的继承方式。它结合了原型链继承和借用构造函数继承的优点,同时避免了它们的缺陷。本文将详细介绍寄生组合继承的概念、实现方式及其优缺点。
一、JavaScript的继承方式回顾
在JavaScript中,常见的继承方式主要有以下几种:
1. 原型链继承(Prototype Inheritance)
原型链继承通过让子类的原型指向父类的实例来实现继承。
function Parent() {
this.name = "Parent";
}
Parent.prototype.sayHello = function () {
console.log("Hello from Parent");
};
function Child() {
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
const child = new Child();
console.log(child.name); // Parent
child.sayHello(); // Hello from Parent
缺点:
- 子类实例共享父类的引用属性,修改一个实例的引用属性会影响所有实例。
- 不能向父类构造函数传参。
2. 借用构造函数继承(Constructor Stealing Inheritance)
借用构造函数继承通过在子类构造函数中调用父类构造函数来实现。
function Parent(name) {
this.name = name

1430

被折叠的 条评论
为什么被折叠?



