寄生组合式继承是目前 javascript 中最推荐、最接近“完美”的继承实现方式,它通过 parent.call(this) 继承实例属性、object.create(parent.prototype) 继承原型方法,避免共享引用类型和父类构造函数重复执行。

寄生组合式继承是目前 JavaScript 中最推荐、最接近“完美”的继承实现方式。它解决了其他方式的核心缺陷:既避免了引用类型属性被所有实例共享的问题,又防止父类构造函数被调用两次,还完整保留了原型链上的方法复用能力。
为什么说它“接近完美”
它把两类继承的优点精准拆分、各司其职:
-
实例属性(如数组、对象、基本值) —— 通过
Parent.call(this, ...)在子类构造函数中单独初始化,保证每个实例独有一份; -
原型方法(如
sayName、validate) —— 通过中间对象只继承一次Parent.prototype,不执行Parent构造逻辑,避免冗余开销和副作用。
关键步骤:三步写出标准实现
不需要第三方库,纯原生 JS 即可完成:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
- 定义一个通用的
inheritPrototype(child, parent)工具函数,用Object.create(parent.prototype)创建干净原型对象,并修正constructor指针; - 在子类构造函数中,用
Parent.call(this, ...)继承父类实例属性(支持传参); - 在子类定义完成后,立即调用
inheritPrototype(Child, Parent),把子类原型安全挂到父类原型链上。
一个可直接运行的完整示例
注意看注释中标出的“关键点”:
function Parent(name) {
this.name = name;
this.colors = ['red', 'blue'];
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name); // ✅ 关键:继承实例属性,且可传参
this.age = age;
}
// ✅ 关键:只继承原型,不执行 Parent()
function inheritPrototype(child, parent) {
const prototype = Object.create(parent.prototype);
prototype.constructor = child;
child.prototype = prototype;
}
inheritPrototype(Child, Parent); // 执行一次,就到位
// ✅ 可安全添加子类特有方法
Child.prototype.sayAge = function() {
console.log(this.age);
};
const c1 = new Child('Alice', 25);
c1.colors.push('green');
const c2 = new Child('Bob', 30);
console.log(c1.colors); // ['red','blue','green']
console.log(c2.colors); // ['red','blue'] —— 不共享 ✅
c1.sayName(); // 'Alice' —— 方法可调用 ✅
c1.sayAge(); // 25 —— 子类方法可用 ✅
和 ES6 class 继承的关系
ES6 的 class extends 底层正是基于寄生组合式继承思想实现的。你写的:
class Child extends Parent {
constructor(name, age) {
super(name); // 等价于 Parent.call(this, name)
this.age = age;
}
}
在编译或运行时,引擎会自动为你完成原型链设置、constructor 修正等操作。所以掌握寄生组合式继承,等于看清了 extends 的本质,遇到 Babel 转译问题、自定义构建流程或需要手写兼容代码时,就能稳住不慌。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










