JavaScript继承的6种实现方式及优缺点对比

作者:半夏时间:2026-11-19 16:11:59浏览:406

系统剖析JavaScript中经典的6种继承实现方式:原型链继承、借用构造函数继承、组合继承、原型式继承、寄生式继承与寄生组合式继承。通过详尽的代码示例、执行输出、内存模型与原型链SVG架构图,全面解析其实现机制、优缺点及选型依据。

JavaScript继承的6种实现方式及优缺点对比
缩略概览:JavaScript 面向对象继承机制全景解析

在面向对象编程中,继承的核心目标是实现代码复用与对象行为特化。与基于类(Class-based)的传统面向对象语言(如 Java、C++)不同,ECMAScript 在规范底层采用的是基于原型(Prototype-based)的继承机制。JavaScript 并没有真正意义上的“类拷贝”行为,而是通过隐藏的 [[Prototype]] 原型链指针,将对象与对象自下而上链接在一起进行属性和方法的动态委托查找。

在 ES6 引入正式的 class 与 extends 语法糖之前,社区在实践中探索并沉淀出了 6 种经典的原型继承实现方式:原型链继承、借用构造函数继承、组合继承、原型式继承、寄生式继承以及寄生组合式继承。本文将针对每一种实现方式,详细拆解其实现原理、标准代码编写、实际执行结果,并系统对比它们在实例属性独立性、方法复用开销、构造函数调用性能等维度的优缺点与底层演进逻辑。

JavaScript继承的6种实现方式及优缺点对比
图1:JavaScript 6种继承范式的推导演进与缺陷解决脉络

一、原型链继承 (Prototype Chain Inheritance)

原型链继承是最基础的继承形态,其核心理念非常直观:直接将子类的原型对象重写为父类的一个新实例(即 Child.prototype = new Parent())。当子类实例访问某个属性或方法时,若实例自身没有定义该属性,JavaScript 引擎就会沿着其原型链向上寻找,从而访问到父类实例及其原型上的属性和方法。

1. 完整代码示例

// 1. 定义父类构造函数
function Parent() {
  this.name = 'Parent';
  this.colors = ['red', 'blue']; // 包含引用类型的属性
}

// 在父类原型上定义共享方法
Parent.prototype.getName = function() {
  return this.name;
};

// 2. 定义子类构造函数
function Child() {
  this.subName = 'Child';
}

// 3. 核心步骤:子类原型指向父类实例
Child.prototype = new Parent();

// 4. 在子类原型上补充自身的方法
Child.prototype.getSubName = function() {
  return this.subName;
};

// 5. 实例化并验证
const child1 = new Child();
const child2 = new Child();

child1.colors.push('green');

console.log('child1.colors:', child1.colors);
console.log('child2.colors:', child2.colors);
console.log('child1.getName():', child1.getName());
console.log('child1 instanceof Parent:', child1 instanceof Parent);
执行输出结果
child1.colors: [ 'red', 'blue', 'green' ]
child2.colors: [ 'red', 'blue', 'green' ]
child1.getName(): Parent
child1 instanceof Parent: true

2. 优缺点分析

  • 优点:
    • 实现极为简洁,直接利用 JavaScript 语言的原型委托机制。
    • 父类原型链上定义的所有方法(如 getName)都可以被所有子类实例复用,不会在每个子类实例中重复创建,内存占用低。
  • 致命缺陷:
    • 引用类型属性全实例共享污染:如上方代码所示,父类中的 colors 数组随 new Parent() 挂载到了 Child.prototype 上,导致所有 Child 实例共享同一个数组内存引用。child1 的修改直接影响了 child2,破坏了实例数据的独立封装性。
    • 子类实例化时无法向父类构造函数传参:执行 new Child() 时,无法将个性化参数动态传递给父类的构造函数 Parent()。若强制传参,则会影响所有由该子类构建出的对象。

二、借用构造函数继承 (Constructor Stealing)

为了解决原型链继承中“引用类型共享污染”和“无法动态传参”的两大痛点,开发者提出了借用构造函数继承(又称经典继承或伪造对象继承)。其核心做法是:在子类的构造函数内部,通过 call() 或 apply() 显式调用父类构造函数,并将当前的 this 上下文绑定进去。

1. 完整代码示例

// 1. 父类构造函数,支持传参
function Parent(name) {
  this.name = name;
  this.colors = ['red', 'blue']; // 每个实例将拥有独立副本
}

// 父类原型方法
Parent.prototype.sayHi = function() {
  return 'Hi, ' + this.name;
};

// 2. 子类构造函数
function Child(name, age) {
  // 核心步骤:在子类中借用父类构造函数执行
  Parent.call(this, name);
  this.age = age;
}

// 3. 实例化测试
const child1 = new Child('Tom', 12);
const child2 = new Child('Jerry', 10);

child1.colors.push('black');

console.log('child1 name/age/colors:', child1.name, child1.age, child1.colors);
console.log('child2 name/age/colors:', child2.name, child2.age, child2.colors);

// 尝试调用父类原型上的方法
try {
  child1.sayHi();
} catch (err) {
  console.log('调用 sayHi 抛出异常:', err.message);
}
执行输出结果
child1 name/age/colors: Tom 12 [ 'red', 'blue', 'black' ]
child2 name/age/colors: Jerry 10 [ 'red', 'blue' ]
调用 sayHi 抛出异常: child1.sayHi is not a function

2. 优缺点分析

  • 优点:
    • 属性绝对隔离:通过 Parent.call(this),父类构造函数中声明的所有属性直接初始化在子类新创建的实例对象上,每个实例都有一份独立的 colors 内存副本,互不干扰。
    • 支持在实例化时向父类传参:子构造函数接受的参数可以直接转发给父构造函数(例如 Parent.call(this, name))。
  • 致命缺陷:
    • 方法无法复用:为了让子类继承父类方法,所有公共方法必须定义在父类构造函数内部。这意味着每创建一个实例,就会重复为该实例分配并创建一套全新的方法函数对象,造成极大的内存浪费。
    • 子类无法访问父类原型方法:由于子类原型 Child.prototype 并未与父类建立任何链条关联,父类原型(Parent.prototype)上定义的方法对子类实例完全不可见。

三、组合继承 (Combination Inheritance)

组合继承(Combination Inheritance,也称伪经典继承)结合了前两者的长处:利用原型链实现对父类原型属性与方法的复用共享,同时利用借用构造函数保证子类实例各自拥有独立的属性副本并支持参数传递。这是在 ES6 出现之前 JavaScript 社区中最常用、接受度最广的一种传统继承模式。

JavaScript继承的6种实现方式及优缺点对比
图2:原型链引用污染与组合继承属性遮蔽内存对比模型

1. 完整代码示例

// 1. 父类构造函数
function Parent(name) {
  this.name = name;
  this.colors = ['red', 'blue'];
}

// 父类原型方法
Parent.prototype.sayName = function() {
  return this.name;
};

// 2. 子类构造函数
function Child(name, age) {
  // 第一次调用父类构造函数:继承实例私有属性并传参
  Parent.call(this, name);
  this.age = age;
}

// 3. 关联原型链:第二次调用父类构造函数,继承父类原型方法
Child.prototype = new Parent();

// 修正 constructor 指向,避免其错误指向 Parent
Child.prototype.constructor = Child;

// 子类原型扩展自身方法
Child.prototype.sayAge = function() {
  return this.age;
};

// 4. 验证测试
const child1 = new Child('Alice', 20);
const child2 = new Child('Bob', 22);

child1.colors.push('yellow');

console.log('child1.colors:', child1.colors);
console.log('child2.colors:', child2.colors);
console.log('child1.sayName():', child1.sayName());
console.log('child1.sayAge():', child1.sayAge());
console.log('child1.constructor === Child:', child1.constructor === Child);
console.log('child1 instanceof Parent:', child1 instanceof Parent);
执行输出结果
child1.colors: [ 'red', 'blue', 'yellow' ]
child2.colors: [ 'red', 'blue' ]
child1.sayName(): Alice
child1.sayAge(): 20
child1.constructor === Child: true
child1 instanceof Parent: true

2. 优缺点分析

  • 优点:
    • 完美融合了原型链与构造函数的优势:实例属性拥有独立隔离的内存作用域,支持实例化动态传参;
    • 原型方法得到全实例共享复用;
    • 原型链关系完整保留,instanceof 和 isPrototypeOf() 均能正确进行类型识别。
  • 主要缺点(效率冗余):
    • 父类构造函数被强制调用了两次:第一次在指定子类原型时(Child.prototype = new Parent()),第二次在子类实例化时(Parent.call(this, name))。
    • 原型上残留同名冗余属性:由于 new Parent() 生成了原型对象,使得 Child.prototype 上也挂载了一份 name 和 colors。虽然子类实例自身的同名属性在查找时会优先匹配(属性遮蔽,Property Shadowing),但这部分无用的原型属性白白占据了内存空间。

四、原型式继承 (Prototypal Inheritance)

2006 年,Douglas Crockford 发表了题为《JavaScript 中的原型式继承》(Prototypal Inheritance in JavaScript)的文章,提出了一种不必预先定义正规自定义类型(构造函数)即可在现有对象之间实现共享复用的继承思路。其本质是对一个现有的基准对象进行浅复制,以其为原型构造出一个新对象。ECMAScript 5 将该思想标准化为了内置的 Object.create() 方法。

1. 完整代码示例

// 原始的 Crockford 原型式函数实现
function object(protoObj) {
  function F() {}     // 创建临时空构造函数
  F.prototype = protoObj; // 构造函数原型指向目标基准对象
  return new F();       // 返回临时实例
}

// 基准原型对象
const person = {
  name: 'Default',
  friends: ['Bob', 'Shelly']
};

// 1. 使用兼容函数实现
const personA = object(person);
personA.name = 'Person A';
personA.friends.push('Rob');

// 2. 使用 ES5 标准 Object.create(proto, [propertiesObject])
const personB = Object.create(person, {
  name: {
    value: 'Person B',
    writable: true,
    enumerable: true
  }
});
personB.friends.push('Linda');

console.log('personA.name / friends:', personA.name, personA.friends);
console.log('personB.name / friends:', personB.name, personB.friends);
console.log('基准对象 person.friends:', person.friends);
执行输出结果
personA.name / friends: Person A [ 'Bob', 'Shelly', 'Rob', 'Linda' ]
personB.name / friends: Person B [ 'Bob', 'Shelly', 'Rob', 'Linda' ]
基准对象 person.friends: [ 'Bob', 'Shelly', 'Rob', 'Linda' ]

2. 优缺点分析

  • 优点:
    • 极端轻量:在仅仅需要让一个对象与另一个对象保持类似结构并继承其能力时,无需编写繁重的构造函数和原型挂载逻辑。
    • ES5 的 Object.create() 原生支持第二个参数直接定义属性描述符,兼顾了属性定义与继承链挂载。
  • 缺点:
    • 本质上依然是原型链的浅映射,基准对象中包含的引用类型属性依然会在所有衍生对象间共享,容易引发状态相互串扰。
    • 无法像构造函数那样轻松封装私有属性和参数初始化逻辑。

五、寄生式继承 (Parasitic Inheritance)

寄生式继承同样由 Douglas Crockford 推广。其设计构想是:创建一个仅用于封装继承过程的工厂函数,在函数内部先利用原型式继承得到一个新对象,随后直接对该对象进行功能增强(扩展属性和方法),最后将其返回。它之所以被称为“寄生”,是因为它的行为模式类似于寄生在原型式继承生成的空宿主对象上,并在外部为其注入功能。

1. 完整代码示例

// 基于原型式继承的内部克隆基底
function createObject(proto) {
  function F() {}
  F.prototype = proto;
  return new F();
}

// 核心:寄生式包装工厂函数
function createEnhancedPerson(original) {
  // 1. 依托现有对象创建基础副本(浅克隆)
  const clone = createObject(original);

  // 2. 寄生式增强:为该新对象挂载专属能力
  clone.sayHello = function() {
    return 'Hello, my name is ' + this.name;
  };

  clone.timestamp = Date.now();

  // 3. 返回增强后的对象
  return clone;
}

// 验证测试
const basePerson = {
  name: 'BaseUser',
  hobbies: ['coding', 'chess']
};

const user1 = createEnhancedPerson(basePerson);
user1.name = 'David';
user1.hobbies.push('running');

const user2 = createEnhancedPerson(basePerson);
user2.name = 'Emma';

console.log('user1.sayHello():', user1.sayHello());
console.log('user2.sayHello():', user2.sayHello());
console.log('user1.hobbies:', user1.hobbies);
console.log('user2.hobbies:', user2.hobbies);
console.log('方法是否为同一引用:', user1.sayHello === user2.sayHello);
执行输出结果
user1.sayHello(): Hello, my name is David
user2.sayHello(): Hello, my name is Emma
user1.hobbies: [ 'coding', 'chess', 'running' ]
user2.hobbies: [ 'coding', 'chess', 'running' ]
方法是否为同一引用: false

2. 优缺点分析

  • 优点:
    • 高度灵活,适合在不改动原有构造函数或目标对象的前提下,为单例对象或由第三方接口返回的对象快速打上补丁、扩展特定方法。
    • 为解决组合继承的二次调用缺陷提供了核心思路工具(即通过工厂函数处理原型副本)。
  • 缺点:
    • 方法无法复用:在工厂函数体内通过 clone.sayHello = function... 挂载的方法,在每次调用 createEnhancedPerson 时都会重新创建一次函数对象。这与“借用构造函数继承”中方法无法复用的缺陷完全一致。
    • 原本挂在 original 对象上的引用属性依然存在共享隐患。

六、寄生组合式继承 (Parasitic Combination Inheritance)

组合继承最大的痛点是父类构造函数被重复执行了两次,并在子类原型上留下了被遮蔽的冗余属性。寄生组合式继承正是针对这一痛点的终极解决方案:通过借用构造函数继承实例属性,同时通过寄生式的方法只拷贝父类原型的副本,将其赋值给子类原型,从而彻底规避调用 new Parent()。

在业界公认的标准中,寄生组合式继承是 ES6 之前 JavaScript 实现继承的最优解。现代 ES6 的 class SubClass extends SuperClass 语法在 Babel 和主流 JS 引擎编译降级后,底层生成的原型链结构就是标准的寄生组合式继承。

JavaScript继承的6种实现方式及优缺点对比
图3:寄生组合式继承的原型链架构与核心实现步骤

1. 完整代码示例

// 核心通用工具函数:继承原型的寄生封装
function inheritPrototype(childFn, parentFn) {
  // 1. 创建父类原型的一个干净浅副本(不调用 parentFn 构造函数)
  const prototype = Object.create(parentFn.prototype);

  // 2. 增强对象:修正因重写原型而丢失的 constructor 属性指向
  prototype.constructor = childFn;

  // 3. 将制作好的纯净原型副本赋值给子类的 prototype
  childFn.prototype = prototype;
}

// 1. 父类构造函数
function Parent(name) {
  this.name = name;
  this.colors = ['red', 'blue'];
}

// 父类原型方法
Parent.prototype.sayName = function() {
  return this.name;
};

// 2. 子类构造函数
function Child(name, age) {
  // 仅在此时调用一次父类构造函数,安全初始化私有字段
  Parent.call(this, name);
  this.age = age;
}

// 3. 关键步骤:调用寄生组合原型关联
inheritPrototype(Child, Parent);

// 4. 子类扩展自己的原型方法
Child.prototype.sayAge = function() {
  return this.age;
};

// 5. 实例化验证
const child1 = new Child('Michael', 25);
const child2 = new Child('Sarah', 28);

child1.colors.push('black');

console.log('child1.name / age / colors:', child1.name, child1.age, child1.colors);
console.log('child2.name / age / colors:', child2.name, child2.age, child2.colors);
console.log('child1.sayName():', child1.sayName());
console.log('child1.sayAge():', child1.sayAge());

// 原型链与类型断言检测
console.log('child1.constructor === Child:', child1.constructor === Child);
console.log('child1 instanceof Child:', child1 instanceof Child);
console.log('child1 instanceof Parent:', child1 instanceof Parent);
console.log('Parent.prototype.isPrototypeOf(child1):', Parent.prototype.isPrototypeOf(child1));
console.log('Child.prototype 自身属性检查 (无冗余):', Object.keys(Child.prototype));
执行输出结果
child1.name / age / colors: Michael 25 [ 'red', 'blue', 'black' ]
child2.name / age / colors: Sarah 28 [ 'red', 'blue' ]
child1.sayName(): Michael
child1.sayAge(): 25
child1.constructor === Child: true
child1 instanceof Child: true
child1 instanceof Parent: true
Parent.prototype.isPrototypeOf(child1): true
Child.prototype 自身属性检查 (无冗余): [ 'constructor', 'sayAge' ]

2. 优缺点分析

  • 优点(无懈可击的高效继承):
    • 高效且无冗余:父类构造函数在整个继承链构建过程中只被执行了 1 次,子类原型 Child.prototype 上只有 constructor 和子类自身定义的方法,完全不存在来自父类实例属性的冗余副本。
    • 原型链完美严密:instanceof、isPrototypeOf() 与 constructor 引用全数准确工作,具备最强的语义正确性。
    • 属性独立与方法复用兼备:实例内部私有属性保持隔离,原型方法实现完全共享。
  • 局限性:
    • 相比于直接赋值,它需要编写或引入 inheritPrototype 工具函数;对于初学者而言,理解 Object.create 和修正 constructor 的必要性存在一定的学习门槛。

七、6种继承方式全维度对比与技术选型

为了直观呈现上述 6 种实现方式的核心差异,我们将实例属性独立性、方法复用率、构造函数调用次数、原型链完整度以及适用场景汇总如下:

JavaScript继承的6种实现方式及优缺点对比
图4:JavaScript 6大继承方式全维度对比与评估矩阵
继承实现方式 属性隔离状态 方法复用性 父构造调用 原型链完整度 实践评级与适用场景
1. 原型链继承 共享污染 共享复用 1 次 正常 不建议用于业务逻辑,仅作原型链机制教学。
2. 借用构造函数 完全隔离 无法复用 1 次 丢失父原型 仅适用于纯数据对象的字段复制,不涉及复杂方法继承。
3. 组合继承 完全隔离 共享复用 2 次 (冗余) 正常 (含遮蔽) 传统方案最广泛选择;对微小内存冗余不敏感时常用。
4. 原型式继承 共享污染 共享复用 0 次 (工厂) 纯对象代理 适用于无构造函数的轻量对象浅拷贝(Object.create)。
5. 寄生式继承 共享污染 无法复用 0 次 (工厂) 纯对象代理 适用于在不构造类的情况下,为已有独立对象附加方法。
6. 寄生组合式 完全隔离 共享复用 1 次 (最优) 完美严密 ES5时代的终极最佳实践,ES6 class extends 的基石。

八、现代工程视点:ES6 Class 与继承底层映射

在 ECMAScript 2015 (ES6) 中,正式引入了 class、extends 以及 super 关键字。很多初学者误以为 JavaScript 由此转变成了基于类的语言,但实际上 ES6 的 class 只是寄生组合式继承的一层优雅语法糖。

观察以下 ES6 继承代码:

class Parent {
  constructor(name) {
    this.name = name;
  }
  sayName() {
    return this.name;
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name); // 底层相当于 Parent.call(this, name)
    this.age = age;
  }
  sayAge() {
    return this.age;
  }
}

当我们使用 Babel 等转译编译器将上述代码转换为 ES5 时,其生成的运行时辅助函数 _inherits 的实现逻辑如下:

function _inherits(subClass, superClass) {
  // 1. 设置原型链:相当于 Object.create(superClass.prototype)
  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      writable: true,
      configurable: true
    }
  });
  // 2. 设置静态方法继承(子构造函数 __proto__ 指向父构造函数)
  if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}

可以看到,现代标准的底层仍然完整延续了寄生组合式继承的思想——通过 Object.create 纯净挂载原型链,通过构造调用绑定自身属性。深刻理解这 6 种实现方式的演进过程,不仅有助于攻克面试与底层技术关卡,更能在编写架构级 JavaScript 代码与分析性能瓶颈时做到心中有数、游刃有余。

作者最新文章
相关文章
更多