组合式继承寄生组合继承es6继承 extends
时间: 2025-01-16 07:55:11 浏览: 42
### JavaScript 不同继承模式的区别
#### 组合式继承
组合式继承利用 `call` 或者 `apply` 来继承父类构造函数的内容,并通过设置子类原型为父类的一个新实例来获取父类的方法。这种方式能够使子类既获得父类的属性又得到其方法。
```javascript
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function () {
return this.name;
};
function Child() {}
// 使用 call 方法让 Parent 的构造器作用于新的 Child 实例上
Child.prototype = new Parent('default'); // 这里创建了一个 Parent 的实例作为 Child 原型
Child.prototype.constructor = Child; // 修正 constructor 属性指向
var childInstance = new Child();
console.log(childInstance.sayName()); // 输出: default
```
这种做法存在一个问题,就是当需要传递参数给父级构造函数时会变得复杂,因为每次都会调用两次父类构造函数——一次是在初始化子类的时候,另一次则是为了建立原型链接[^2]。
#### 寄生组合继承
为了避免上述问题,在寄生组合继承中只会在必要时候调用一次父类构造函数。具体来说,不是简单地把整个父类实例赋值给子类的 prototype ,而是仅复制那些必要的部分到一个新的对象上去,再把这个新对象设为子类的 prototype 。这使得我们可以更加灵活地控制哪些特性应该被共享或独立出来。
```javascript
function inheritPrototype(subType, superType){
let prototype = Object.create(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}
inheritPrototype(Child, Parent);
let childInst = new Child();
console.log(childInst instanceof Parent); // true
```
这种方法有效地解决了重复调用父类构造函数的问题,同时也保持了原有功能不变[^4]。
#### ES6 中的 `extends` 关键字
随着 ECMAScript 6 (ES6) 的推出,JavaScript 提供了一种更为直观的方式来处理类之间的关系 —— 即使用 `class` 和 `extends` 关键字来进行面向对象编程中的继承操作。它简化了许多传统方式下的繁琐过程,并提供了更好的可读性和维护性。
```javascript
class Animal {
constructor(sound) {
this.sound = sound;
}
makeSound() {
console.log(`The animal makes a ${this.sound}`);
}
}
class Dog extends Animal {
bark() {
console.log("Woof!");
}
// 调用父类构造函数
constructor(){
super('bark');
}
}
const myDog = new Dog();
myDog.makeSound(); // The animal makes a bark
myDog.bark(); // Woof!
```
这里的关键在于 `super()` 函数的应用;它允许我们在子类内部访问和调用来自父类的方法与属性。此外,由于语法糖的存在,开发者不再需要显式管理复杂的原型链结构,从而降低了出错的可能性[^3]。
阅读全文
相关推荐

















