实现继承 js
原型链继承
通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法,但所有子类实例共享父类实例的属性,可能导致修改污染。
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello from ' + this.name);
};
function Child() {}
Child.prototype = new Parent(); // 原型链继承
const child = new Child();
child.sayHello(); // 输出: Hello from Parent
构造函数继承
在子类构造函数中调用父类构造函数,通过call或apply绑定this。子类实例拥有独立的父类属性,但无法继承父类原型上的方法。
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.sayHello = function() {
console.log('Hello from ' + this.name);
};
function Child(name) {
Parent.call(this, name); // 继承属性
}
Child.prototype = new Parent(); // 继承方法
const child = new Child('Child');
child.sayHello(); // 输出: Hello from Child
寄生组合继承
通过Object.create创建父类原型的副本作为子类原型,避免调用父类构造函数。这是ES5中最理想的继承方式。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHello = function() {
console.log('Hello from ' + 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.sayHello(); // 输出: Hello from Child
ES6类继承
使用extends和super语法糖实现继承,底层仍基于寄生组合继承。代码更简洁,支持静态方法继承。

class Parent {
constructor(name) {
this.name = name;
}
sayHello() {
console.log('Hello from ' + this.name);
}
}
class Child extends Parent {
constructor(name) {
super(name); // 调用父类构造函数
}
}
const child = new Child('Child');
child.sayHello(); // 输出: Hello from Child






