js 实现 extends
实现继承的方式
在 JavaScript 中,可以通过多种方式实现继承。以下是几种常见的方法:
原型链继承
通过将子类的原型指向父类的实例来实现继承。
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child() {}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
const child = new Child();
child.sayName(); // 输出 'Parent'
构造函数继承
在子类的构造函数中调用父类的构造函数,使用 call 或 apply 方法。
function Parent(name) {
this.name = name;
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
const child = new Child('Child', 10);
console.log(child.name); // 输出 'Child'
组合继承
结合原型链继承和构造函数继承的优点。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
const child = new Child('Child', 10);
child.sayName(); // 输出 'Child'
寄生组合继承
优化组合继承,避免重复调用父类构造函数。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
const child = new Child('Child', 10);
child.sayName(); // 输出 'Child'
ES6 的 class 继承
使用 class 和 extends 关键字实现继承。

class Parent {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
}
const child = new Child('Child', 10);
child.sayName(); // 输出 'Child'
选择继承方式的建议
- 原型链继承简单但可能导致引用类型共享问题。
- 构造函数继承无法继承父类原型上的方法。
- 组合继承是较为常用的方式,但会调用两次父类构造函数。
- 寄生组合继承是组合继承的优化版本,推荐使用。
- ES6 的
class继承语法简洁,推荐在现代项目中使用。






