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"
原型式继承
基于现有对象创建新对象,使用 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.sayHi = function() {
console.log('hi');
};
return child;
}
const parent = { name: 'parent' };
const child = createChild(parent);
寄生组合式继承
目前最理想的继承方式。通过借用构造函数继承属性,通过混合式原型链继承方法。只调用一次父类构造函数,避免不必要的属性创建。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name) {
Parent.call(this, name);
}
// 使用 Object.create 避免调用 Parent 构造函数
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); // 必须调用 super
}
}
const child = new Child('child');
child.sayName(); // 输出 "child"






