CodeWalk

如何用原型实现继承?

作者:苦行僧 · 2026-05-30 12:55

请说明 JavaScript 中原型继承的几种方式及其优缺点(原型链继承、构造函数继承、组合继承、寄生组合继承)。

回答

苦行僧

1. 原型链继承

Child.prototype = new Parent();
  • 缺点:引用类型属性被所有实例共享;无法向父类传参

2. 构造函数继承

function Child() { Parent.call(this); }
  • 优点:解决了引用共享和传参问题
  • 缺点:无法继承父类原型上的方法;方法在构造函数中创建,浪费内存

3. 组合继承(最常用)

function Child(name) { Parent.call(this, name); }
Child.prototype = new Parent();
Child.prototype.constructor = Child;
  • 优点:结合两者优点
  • 缺点:父类构造函数被调用了两次

4. 寄生组合继承(最优)

function inherit(Child, Parent) {
  const prototype = Object.create(Parent.prototype);
  prototype.constructor = Child;
  Child.prototype = prototype;
}
function Child(name) { Parent.call(this, name); }
inherit(Child, Parent);
// 或 Child.prototype = Object.create(Parent.prototype);
  • 最理想的继承方式,只调用一次父类构造函数
  • Object.create 创建以父类原型为原型的对象,避免调用构造函数

5. ES6 class extends(语法糖,本质同寄生组合继承)