怎样实现js的继承
原型链继承
通过将子类的原型指向父类的实例实现继承。子类实例通过原型链访问父类的属性和方法。
function Parent() {
this.name = 'parent';
}
Parent.prototype.say = function() {
console.log(this.name);
};
function Child() {}
Child.prototype = new Parent(); // 核心步骤
const child = new Child();
child.say(); // 输出'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.say = function() {
console.log(this.name);
};
function Child(name) {
Parent.call(this, name); // 第一次调用
}
Child.prototype = new Parent(); // 第二次调用
const child = new Child('child');
child.say(); // 输出'child'
原型式继承
基于现有对象创建新对象,使用Object.create()实现。适合不需要单独构造函数的场景。
const parent = {
name: 'parent',
say: function() {
console.log(this.name);
}
};
const child = Object.create(parent); // 核心步骤
child.name = 'child';
child.say(); // 输出'child'
寄生式继承
在原型式继承基础上增强对象,添加额外方法。适用于需要为对象添加特殊方法的场景。

function createAnother(original) {
const clone = Object.create(original);
clone.sayHi = function() { // 添加新方法
console.log('hi');
};
return clone;
}
const parent = { name: 'parent' };
const child = createAnother(parent);
child.sayHi(); // 输出'hi'
寄生组合式继承
目前最理想的继承方式,通过借用构造函数继承属性,通过原型链混成形式继承方法。只调用一次父类构造函数。
function inheritPrototype(child, parent) {
const prototype = Object.create(parent.prototype); // 创建父类原型副本
prototype.constructor = child; // 修正constructor
child.prototype = prototype; // 赋值给子类原型
}
function Parent(name) {
this.name = name;
}
Parent.prototype.say = function() {
console.log(this.name);
};
function Child(name) {
Parent.call(this, name);
}
inheritPrototype(Child, Parent); // 核心步骤
const child = new Child('child');
child.say(); // 输出'child'
ES6 Class继承
使用extends关键字实现类继承,语法更简洁直观。底层实现仍然是基于原型链。
class Parent {
constructor(name) {
this.name = name;
}
say() {
console.log(this.name);
}
}
class Child extends Parent { // 核心步骤
constructor(name) {
super(name); // 必须调用super
}
}
const child = new Child('child');
child.say(); // 输出'child'





