javaScript中常见的继承方式包括原型链继承、构造函数继承、组合继承、寄生组合继承和es6 class继承。1. 原型链继承通过子类原型指向父类实例实现,可复用方法但共享引用属性且无法传参。2. 构造函数继承在子类中调用父类call/apply,可传参并独立属性,但无法继承原型方法。3. 组合继承结合前两者优点,既能传参又能继承原型方法,但父类构造函数被调用两次。4. 寄生组合继承通过Object.create优化,仅调用一次父类构造函数,是当前最推荐的方式。5. ES6 class继承使用extends和super,语法清晰,底层基于寄生组合继承,支持静态方法和getter/setter,需注意super必须在子类constructor中调用。实际开发中推荐使用class或寄生组合继承。

javascript 中实现继承的方式有多种,每种方式都有其特点和适用场景。由于 js 是基于原型的语言,没有传统类继承的概念(ES6 class 之前),因此继承机制主要通过原型链和构造函数模拟实现。以下是几种常见的继承方式及其核心原理。
1. 原型链继承
通过将子类的原型指向父类的实例来实现继承。
立即学习“Java免费学习笔记(深入)”;
}
Parent.prototype.getName = function() {
return this.name;
};
function Child() {}
Child.prototype = new Parent(); // 核心:子类原型是父类实例
const child = new Child();
console.log(child.getName()); // ‘parent’
优点: 简单,支持方法复用。
缺点: 所有子类实例共享父类引用类型属性;创建子类实例时不能向父类构造函数传参。
2. 构造函数继承(经典继承)
在子类构造函数中调用父类构造函数,使用 call 或 apply 绑定 this。
function Parent(name) {
this.name = name;
this.colors = [‘red‘, ‘blue’];
}
function Child(name) {
Parent.call(this, name); // 核心:借用构造函数
}
const c1 = new Child(‘child1’);
c1.colors.push(‘green’);
const c2 = new Child(‘child2’);
console.log(c1.colors); // [‘red’, ‘blue’, ‘green’]
console.log(c2.colors); // [‘red’, ‘blue’]
优点: 可传参,每个实例有独立的属性副本,避免引用类型污染。
缺点: 父类原型上的方法无法被子类继承,方法不能复用。
3. 组合继承(最常用)
结合原型链继承和构造函数继承,发挥两者优点。
function Parent(name) {
this.name = name;
this.colors = [‘red’, ‘blue’];
}
Parent.prototype.getName = function() {
return this.name;
};
function Child(name, age) {
Parent.call(this, name); // 第二次调用 Parent()
this.age = age;
}
Child.prototype = new Parent(); // 第一次调用 Parent()
Child.prototype.constructor = Child;
Child.prototype.getAge = function() {
return this.age;
};
优点: 实例有独立属性,又能继承原型方法,支持传参。
缺点: 父类构造函数被调用两次,可能造成性能浪费。
4. 寄生组合继承(推荐)
优化组合继承,避免重复调用父类构造函数。
function inheritPrototype(Child, Parent) {
const prototype = Object.create(Parent.prototype);
prototype.constructor = Child;
Child.prototype = prototype;
}
function Parent(name) {
this.name = name;
}
Parent.prototype.getName = function() {
return this.name;
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
inheritPrototype(Child, Parent); // 核心:不直接 new Parent()
优点: 高效,只调用一次父类构造函数,完全继承原型方法。
这是目前最理想的继承模式。
5. ES6 Class 继承
ES6 引入 class 和 extends 关键字,语法更清晰,底层仍是寄生组合继承。
class Parent {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class Child extends Parent {
constructor(name, age) {
super(name); // 调用父类 constructor
this.age = age;
}
getAge() {
return this.age;
}
}
优点: 语法简洁,语义清晰,支持静态方法、getter/setter 等。
注意: 子类 constructor 中必须调用 super(),否则无法使用 this。
基本上就这些。从原型链到 class,JS 的继承方式不断演进,理解底层原理有助于写出更健壮的代码。寄生组合继承和 class 继承是实际开发中最常用的方案。不复杂但容易忽略细节,比如 constructor 修复和 super 调用时机。


