js实现继承怎么实现
原型链继承
通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。
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;
}
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.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"
缺点:父类构造函数被调用两次(Parent.call 和 new Parent()),性能损耗。

原型式继承
基于已有对象创建新对象,通过 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.newMethod = function() {
console.log('New method');
};
return child;
}
const parent = { name: 'Parent' };
const child = createChild(parent);
child.newMethod(); // 输出 "New method"
缺点:与原型式继承类似,无法复用方法。
寄生组合式继承
最优解决方案,通过 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 和 super 语法糖实现继承,本质是寄生组合式继承的语法封装。
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 标准。






