继承实现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;
}
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);
child.sayHi(); // 输出 "Hi"
寄生组合式继承
最优解决方案,避免组合继承中父类构造函数被调用两次的问题。
function inheritPrototype(Child, Parent) {
const prototype = Object.create(Parent.prototype); // 创建父类原型的副本
prototype.constructor = Child; // 修正构造函数指向
Child.prototype = prototype; // 赋值给子类原型
}
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name) {
Parent.call(this, name); // 继承属性
}
inheritPrototype(Child, Parent); // 继承方法
const child = new Child('Child');
child.sayName(); // 输出 "Child"
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"
优势:语法简洁,底层仍基于原型链实现。






