继承实现js
继承的概念
继承是面向对象编程的核心概念之一,允许一个类(子类)继承另一个类(父类)的属性和方法,从而实现代码复用和层次化设计。
原型链继承
通过原型链实现继承,子类的原型指向父类的实例。这是 JavaScript 中最基本的继承方式。
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child() {
this.childName = 'Child';
}
Child.prototype = new Parent(); // 继承实现
const child = new Child();
child.sayName(); // 输出 "Parent"
构造函数继承
在子类构造函数中调用父类构造函数,使用 call 或 apply 方法实现属性继承。
function Parent(name) {
this.name = name;
}
function Child(name, age) {
Parent.call(this, name); // 继承属性
this.age = age;
}
const child = new Child('Alice', 10);
console.log(child.name); // 输出 "Alice"
组合继承
结合原型链继承和构造函数继承,既能继承父类原型的方法,又能继承实例属性。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name); // 继承属性
this.age = age;
}
Child.prototype = new Parent(); // 继承方法
Child.prototype.constructor = Child; // 修复构造函数指向
const child = new Child('Bob', 12);
child.sayName(); // 输出 "Bob"
原型式继承
利用 Object.create() 方法创建一个新对象,以现有对象作为原型。
const parent = {
name: 'Parent',
sayName: function() {
console.log(this.name);
}
};
const child = Object.create(parent);
child.name = 'Child';
child.sayName(); // 输出 "Child"
寄生组合式继承
优化组合继承,避免重复调用父类构造函数,减少性能开销。
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, age) {
Parent.call(this, name);
this.age = age;
}
inheritPrototype(Child, Parent);
const child = new Child('Charlie', 15);
child.sayName(); // 输出 "Charlie"
ES6 类继承
使用 class 和 extends 关键字实现继承,语法更简洁直观。

class Parent {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}
class Child extends Parent {
constructor(name, age) {
super(name); // 调用父类构造函数
this.age = age;
}
}
const child = new Child('Dave', 20);
child.sayName(); // 输出 "Dave"
注意事项
- 原型链继承会导致引用类型的属性被所有实例共享。
- 构造函数继承无法继承父类原型上的方法。
- 组合继承会调用两次父类构造函数,可能影响性能。
- ES6 类继承是语法糖,底层仍基于原型链实现。






