在JavaScript中,继承是指一个对象可以使用另一个对象的属性和方法。由于语言设计基于原型而非类,实现继承的方式有多种,理解它们有助于编写可维护的代码。

一、原型链继承
最基础的继承方式是将子类型的原型指向父类型的实例,从而形成原型链。
function Parent() {
this.name = 'parent';
}
Parent.prototype.say = function() {
return this.name;
};
function Child() {}
// 子构造函数的原型指向父实例
Child.prototype = new Parent();
var c = new Child();
console.log(c.say()); // parent
缺点是所有子实例共享父实例的引用属性,且无法向父构造函数传参。
二、构造函数借用
在子构造函数中调用父构造函数,可解决传参与引用共享问题。
function Parent(name) {
this.name = name;
}
function Child(name) {
// 借用父类构造函数
Parent.call(this, name);
}
var c = new Child('tom');
console.log(c.name); // tom
但这种方法无法继承父类原型上的方法。
三、组合继承
结合原型链与构造函数借用,是最常用的传统方案。
function Parent(name) {
this.name = name;
}
Parent.prototype.say = function() {
return this.name;
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var c = new Child('lucy', 12);
console.log(c.say()); // lucy
四、原型式与寄生式继承
利用Object.create可基于已有对象创建新对象,属于原型式继承。
var parent = { name: 'p', list: [] };
var child = Object.create(parent);
child.name = 'c';
console.log(child.name); // c
寄生式继承则是在此基础上增强对象,封装创建过程。
五、ES6的class继承
现代开发推荐使用class与extends语法,底层仍是原型机制。
class Parent {
constructor(name) {
this.name = name;
}
say() {
return this.name;
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
}
const c = new Child('jack', 20);
console.log(c.say()); // jack
六、方法对比
| 方式 | 优点 | 缺点 |
|---|---|---|
| 原型链 | 写法简单 | 引用属性共享 |
| 构造函数借用 | 可传参 | 不继承原型方法 |
| 组合继承 | 较完整 | 父类构造调用两次 |
| class继承 | 语义清晰 | 旧环境需编译 |
根据项目运行环境与团队习惯,选择合适的继承写法即可。
JavaScriptinheritanceprototype_chain修改时间:2026-07-27 04:27:16