js实现继承的方式
在 JavaScript 中,实现继承的方式有多种,以下是常见的几种方法及其实现细节:
原型链继承
通过将子类的原型对象指向父类的实例来实现继承。
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'
特点
- 子类实例共享父类原型上的属性和方法。
- 无法向父类构造函数传参。
构造函数继承
在子类构造函数中调用父类构造函数,并通过 call 或 apply 改变 this 指向。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name) {
Parent.call(this, name); // 继承父类属性
}
const child = new Child('child');
console.log(child.name); // 'child'
child.sayName(); // 报错,无法继承父类原型方法
特点
- 可以传递参数给父类构造函数。
- 无法继承父类原型上的方法。
组合继承
结合原型链继承和构造函数继承,既继承属性又继承方法。
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'
特点
- 解决了构造函数继承无法继承原型方法的问题。
- 父类构造函数会被调用两次,效率较低。
原型式继承
利用 Object.create() 基于现有对象创建新对象。
const parent = {
name: 'parent',
sayName: function() {
console.log(this.name);
}
};
const child = Object.create(parent);
child.name = 'child';
child.sayName(); // 'child'
特点
- 适用于简单对象继承。
- 无法复用构造函数逻辑。
寄生式继承
在原型式继承的基础上增强对象。
function createChild(parent) {
const child = Object.create(parent);
child.sayHello = function() {
console.log('Hello');
};
return child;
}
const parent = { name: 'parent' };
const child = createChild(parent);
child.sayHello(); // 'Hello'
特点
- 可以扩展对象功能。
- 方法无法复用,每个实例都会创建新方法。
寄生组合式继承
结合组合继承和寄生式继承,避免重复调用父类构造函数。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name) {
Parent.call(this, name); // 继承属性
}
Child.prototype = Object.create(Parent.prototype); // 继承原型方法
Child.prototype.constructor = Child; // 修复构造函数指向
const child = new Child('child');
child.sayName(); // 'child'
特点
- 只调用一次父类构造函数,效率更高。
- 是 JavaScript 中最理想的继承方式。
ES6 类继承
使用 class 和 extends 语法糖实现继承。
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'
特点

- 语法简洁,符合现代 JavaScript 开发习惯。
- 底层仍然是基于原型链实现。
以上方法各有适用场景,选择时需根据具体需求权衡。






