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方法实现属性继承。

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(); // 报错,无法继承原型方法
组合继承
结合原型链继承和构造函数继承,既能继承属性也能继承方法。
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实现。

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'
寄生组合式继承
最优的继承方式,避免了组合继承中调用两次父类构造函数的问题。
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语法是推荐的现代写法。






