js 实现 extends
实现 JavaScript 中的继承(extends)
在 JavaScript 中,可以通过多种方式实现继承。以下是几种常见的方法:
原型链继承
通过将子类的原型指向父类的实例来实现继承。
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child() {
this.name = 'Child';
}
Child.prototype = new Parent();
const child = new Child();
child.sayName(); // 输出 'Child'
构造函数继承
在子类构造函数中调用父类构造函数,使用 call 或 apply 方法。
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');
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();
Child.prototype.constructor = Child;
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 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'
ES6 的 class 和 extends
使用 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'
注意事项
- 原型链继承会导致所有子类实例共享父类实例的属性,可能导致意外修改。
- 构造函数继承无法继承父类原型上的方法。
- 组合继承会调用两次父类构造函数,可能影响性能。
- 寄生组合式继承是目前最理想的继承方式。
- ES6 的
class和extends语法简洁,但本质仍是基于原型的继承。






