寄生组合继承中子类原型的constructor必须手动修正为子类本身,否则默认指向父类;因object.create(parent.prototype)创建的对象constructor继承自parent.prototype,需显式赋值child.prototype.constructor = child。

在寄生组合继承中,子类原型的 constructor 必须手动修正为子类本身,否则它会指向父类构造函数——这是最容易被忽略但至关重要的一步。
为什么 constructor 会出错?
寄生组合继承通过 Object.create(Parent.prototype) 创建子类原型对象,而该对象的 constructor 属性默认继承自 Parent.prototype(即指向 Parent),并不会自动变成子类构造函数。
正确设置 constructor 的标准写法
在用 Object.create 设置子类原型后,立即显式赋值:
Child.prototype = Object.create(Parent.prototype);Child.prototype.constructor = Child;
这两行缺一不可。第二步不能省略,也不能写成 Child.constructor = Child(那是修改构造函数自身的属性,无效)。
更健壮的封装方式(推荐)
把继承逻辑抽成工具函数,避免每次重复写两行:
function inherit(Child, Parent) {
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
// 可选:设置 __proto__ 兼容性(仅旧环境需考虑)
if (Object.setPrototypeOf) {
Object.setPrototypeOf(Child.prototype, Parent.prototype);
}
}
使用时:inherit(Student, Person); —— 简洁、统一、不易漏。
验证是否设置成功
可通过以下方式快速检查:
-
new Student().__proto__.constructor === Student→ 应返回true -
Student.prototype.constructor === Student→ 应返回true - 若错误,
new Student().constructor会返回Person,导致instanceof虽然正常,但 JSON 序列化、反射、框架识别等场景可能出问题
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











