寄生组合式继承是es5中最理想的继承方式,它通过object.create(parent.prototype)避免父构造函数重复调用,既实现实例属性隔离又复用原型方法,且修正constructor指向。

寄生组合式继承是 ES5 中公认最理想的继承实现方式,它融合了构造函数继承的实例属性隔离能力与原型链继承的方法复用优势,同时规避了组合继承中父类构造函数被调用两次的问题。
为什么寄生组合式继承更“完美”
它解决了其他方式的关键缺陷:
- 不像原型链继承那样导致引用类型属性(如数组、对象)被所有子实例共享
- 不像构造函数继承那样无法继承父类原型上的方法(比如 sayName)
- 不像组合继承那样在设置原型和初始化实例时重复执行父构造函数(一次在 Child.prototype = new Parent(),一次在 Parent.call(this))
核心实现步骤
关键在于用 Object.create(Parent.prototype) 替代 new Parent() 来设置子类原型,从而避免触发父类构造逻辑。
Java Maven 项目审查工作流的通用输入处理。当 Java Maven 项目以 ZIP压缩包或 GitLab 仓库 URL 形式提供且需要...时使用。
- 在子类构造函数中用 Parent.call(this, ...args) 继承实例属性(确保每个实例独有)
- 用 Object.create(Parent.prototype) 创建干净的原型对象,只继承方法不执行父构造函数
- 手动将 Child.prototype.constructor 指回 Child,防止 constructor 被覆盖为 Parent
典型代码结构
以 Parent 和 Child 为例:
function Parent(name) {
this.name = name;
this.colors = ['red', 'blue'];
}
Parent.prototype.say = function() { console.log('Hello, ' + this.name); };
function Child(name, age) {
Parent.call(this, name); // 实例属性继承
this.age = age;
}
// 关键:不 new Parent(),而是基于其 prototype 创建新对象
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child; // 修正 constructor
Child.prototype.info = function() { console.log(this.name + ', ' + this.age); };
效果验证要点
这样实现后可确认以下行为正常:
- 子实例能调用父类原型方法(child.say() 成功)
- 子实例拥有独立的实例属性(child1.colors.push('green') 不影响 child2.colors)
- 子实例能向父类构造函数传参(new Child('Alice', 25) 中 name 正确传递)
- instanceof 和 isPrototypeOf 判断准确(child instanceof Parent === true)
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










