js实现继承原理
JavaScript 继承的实现原理
JavaScript 的继承基于原型链机制,主要通过原型对象(prototype)实现。以下是常见的几种继承方式及其原理:
原型链继承
通过将子类的原型指向父类的实例实现继承。
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child() {}
Child.prototype = new Parent(); // 原型链继承
const child = new Child();
child.sayName(); // 输出 "Parent"
- 优点:简单直观
- 缺点:所有子类实例共享父类引用属性
构造函数继承
在子类构造函数中调用父类构造函数。
function Parent(name) {
this.name = name;
}
function Child(name) {
Parent.call(this, name); // 构造函数继承
}
const child = new Child('Child');
console.log(child.name); // 输出 "Child"
- 优点:可向父类传参,避免引用属性共享
- 缺点:无法继承父类原型上的方法
组合继承
结合原型链继承和构造函数继承。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name) {
Parent.call(this, name); // 构造函数继承
}
Child.prototype = new Parent(); // 原型链继承
const child = new Child('Child');
child.sayName(); // 输出 "Child"
- 优点:结合两种继承方式的优点
- 缺点:父类构造函数被调用两次
原型式继承
基于已有对象创建新对象。
const parent = {
name: 'Parent',
sayName: function() {
console.log(this.name);
}
};
const child = Object.create(parent);
child.name = 'Child';
child.sayName(); // 输出 "Child"
- 优点:简单灵活
- 缺点:与原型链继承类似,存在引用属性共享问题
寄生组合式继承
目前最理想的继承方式。
function inheritPrototype(child, parent) {
const prototype = Object.create(parent.prototype);
prototype.constructor = child;
child.prototype = prototype;
}
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name) {
Parent.call(this, name);
}
inheritPrototype(Child, Parent);
const child = new Child('Child');
child.sayName(); // 输出 "Child"
- 优点:只调用一次父类构造函数,避免创建多余属性
- 缺点:实现稍复杂
ES6 class 继承
ES6 引入的 class 语法糖。

class Parent {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}
class Child extends Parent {
constructor(name) {
super(name);
}
}
const child = new Child('Child');
child.sayName(); // 输出 "Child"
- 优点:语法简洁,更接近传统面向对象语言
- 缺点:本质仍是原型继承的语法糖
每种继承方式都有其适用场景,理解其原理有助于根据实际需求选择最合适的实现方式。






