js实现继承怎么实现的
在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改变this指向。子类可以继承父类实例属性,但无法继承父类原型上的方法。
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();
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 createChild(parent) {
const child = Object.create(parent);
child.sayHello = function() {
console.log('Hello');
};
return child;
}
const parent = { name: 'parent' };
const child = createChild(parent);
child.sayHello(); // 'Hello'
寄生组合式继承
最优的继承方式,避免组合继承中两次调用父类构造函数的问题。通过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继承
使用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继承是目前推荐的方式,语法简洁且功能完善。






