js实现extends
实现继承的方式
在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方法。这种方法解决了引用类型共享的问题,但无法继承父类原型上的方法。
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(); // Error: child.sayName is not a function
组合继承 结合原型链继承和构造函数继承,既能继承父类实例属性,又能继承父类原型上的方法。但会调用两次父类构造函数。

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来优化组合继承,避免重复调用父类构造函数。这是目前最理想的继承方式。
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关键字实现继承,语法更简洁,底层仍然是基于原型链的继承。
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类继承语法更现代,推荐在新项目中使用。






