使用 ES5 实现一个寄生组合式继承,并解释如何避免两次调用父类构造函数

解读

国内一线/二线厂 Node.js 后端面试中,ES5 手写继承是“必背八股”之一。
寄生组合式继承(Parasitic Combination Inheritance)被视为 ES5 时代“最干净”的继承方案,它既能把父类原型方法复用到子类实例,又不会在子类实例上冗余一份父类实例属性。
核心考点:

  1. 能否一次性写出无语法错误的 ES5 兼容代码(不能出现 class、=>、let/const)。
  2. 能否指出“组合继承”里两次调用 Parent 构造函数(一次是 Parent.call,一次是 new Parent)带来的性能/内存隐患,并用 Object.create 切断原型链直接构造过程,把两次减为一次。
  3. 是否熟悉 Node.js 场景下原型链污染、隐藏类(Hidden Class)失效对性能的影响,从而解释“为什么不用默认 new Parent() 做原型”。

知识点

  1. 构造函数、原型对象、实例,三者关系。
  2. new 运算符背后四步:创建空对象 → 链接原型 → 绑定 this → 返回对象。
  3. Object.create(polyfill) 如何手动指定原型且跳过构造函数。
  4. 组合继承(Combination Inheritance)(Parent.call + new Parent)为何多一次构造调用。
  5. 寄生组合式继承 = 原型继承 + 工厂函数,只拿原型不执行构造函数。
  6. 在 V8 下,重复属性会退化隐藏类,Node.js 高并发服务中应尽量避免。

答案

// 工具函数:创建中间对象,原型指向 parentProto,自身干净无实例属性
function createInheritance(proto) {
  function F() {}   // 空构造函数
  F.prototype = proto;
  return new F();   // 只借原型,不执行父类逻辑
}

// 父类
function Parent(name) {
  this.name = name;
  this.colors = ['red', 'blue'];
}
Parent.prototype.getName = function () {
  return this.name;
};

// 子类
function Child(name, age) {
  // 1. 继承实例属性,仅此一次调用父类构造函数
  Parent.call(this, name);
  this.age = age;
}

// 2. 继承原型方法,不再次调用 Parent
Child.prototype = createInheritance(Parent.prototype);

// 3. 修复 constructor 指向
Child.prototype.constructor = Child;

// 4. 子类扩展方法
Child.prototype.getAge = function () {
  return this.age;
};

// 测试
var c1 = new Child('tom', 18);
var c2 = new Child('jerry', 20);
c1.colors.push('green');
console.log(c1.colors); // ["red","blue","green"]
console.log(c2.colors); // ["red","blue"]  互不影响
console.log(c1.getName()); // tom
console.log(c1 instanceof Child); // true
console.log(c1 instanceof Parent); // true

如何避免两次调用 Parent 构造函数:

  • 组合继承里 Child.prototype = new Parent() 会执行一次 Parent,而 Parent.call(this) 又执行一次,导致父类初始化代码跑两遍,且原型上可能挂一堆不必要的实例属性。
  • 寄生组合式用 createInheritance(Parent.prototype)(或 ES5 的 Object.create(Parent.prototype))只复制原型链引用,不触发 Parent,于是整个继承过程只保留 Parent.call(this) 这一次真正初始化,从而避免重复调用。

拓展思考

  1. 在 Node.js 高并发长连接服务(如 WebSocket 网关)里,若每个连接都新建子类实例,重复的属性写入会使 V8 隐藏类频繁迁移,导致性能回退;寄生组合式继承保证原型只读共享、实例属性一次性初始化,可减轻隐藏类压力。
  2. 如果运行环境低于 Node 0.10(无原生 Object.create),上述 createInheritance 就是稳妥 polyfill;但若支持 Node 4+,可直接 Child.prototype = Object.create(Parent.prototype),再补 constructor 即可。
  3. 进入 ES6 之后,官方 class extends 语法糖在 V8 内部同样采用“一次构造 + 原型链设置”思想,与寄生组合式等价;理解 ES5 手写版本,有助于调试转译后代码及在 Serverless 冷启动场景下减少 Babel helpers 体积。