推荐使用 ES6 class + extends 实现继承,语义清晰且兼容性好;子类 constructor 中须首行调用 super(),通过 super.方法名() 调用父类方法;底层仍基于原型链,class 是语法糖。
JavaScript 中实现继承有多种方式,核心目标是让子类能复用父类的属性和方法,并支持原型链查找。现代开发中推荐使用 ES6 class + extends,但理解底层原理(如原型链、构造函数调用)仍很重要。
使用 class 和 extends 关键字,配合 super() 调用父类构造函数,语义明确、可读性强,且被所有现代浏览器和 Node.js 支持。
super(),否则无法访问 this
super.方法名() 在子类中调用class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // 必须调用
this.breed = breed;
}
speak() {
super.speak(); // 可调用父类方法
console.log(`${this.name} barks`);
}
}
通过将子类的 prototype 指向父类的一个实例来实现继承,使子类实例能沿原型链访问父类原型上的方法。
Object.create() 避免直接 new 父类带来的副作用function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + ' speaks');
};
function Dog(name, breed) {
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.
constructor = Dog; // 修复 constructor 指向
Dog.prototype.speak = function() {
Animal.prototype.speak.call(this);
console.log(this.name + ' barks');
};
在子类构造函数中用 Parent.call(this, ...) 调用父类构造函数,实现对父类实例属性的继承(不继承原型方法)。
function Animal(name) {
this.name = name;
this.colors = ['black', 'white'];
}
Animal.prototype.speak = function() {
console.log(this.name + ' speaks');
};
function Dog(name, breed) {
Animal.call(this, name); // 继承实例属性
this.breed = breed;
}
// 再通过原型链继承方法
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
class 并未改变 JavaScript 的原型继承本质。Babel 编译后,extends 会生成类似 Object.setPrototypeOf(Sub.prototype, Super.prototype) 的逻辑,并确保构造函数正确链接。
instanceof 判断继承关系static 方法继承(子类可直接调用父类静态方法)__proto__ 或 prototype.__proto__ 手动修改原型链,既不标准也不可靠。
不复杂但容易忽略:继承的关键不在“怎么写”,而在“是否真正理解 this 绑定、原型链查找顺序、构造函数执行时机”。掌握一种主流方式(如 class extends),再了解其背后机制,就能应对绝大多数场景。