怎样实现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();
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',
sayName: function() {
console.log(this.name);
}
};
const child = createChild(parent);
child.sayName(); // 输出 '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类继承
使用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类继承是目前最推荐的方式,语法简洁且功能强大。






