原型链继承中,必须手动修复子类prototype的constructor指向自身,推荐用Object.create(Parent.prototype)构建原型链并确保末端连至Object.prototype,ES6 class仍需维护原型一致性。

原型链继承中,原型对象的一致性维护,核心在于确保子构造函数的 prototype 正确指向父类原型,并且其 constructor 属性准确回指自身——否则实例的类型识别、方法调用链和调试体验都会出问题。
constructor 指向必须手动修复
当使用 Child.prototype = new Parent() 建立继承时,Child.prototype.constructor 会变成 Parent,因为新原型是 Parent 的一个实例,而该实例的 constructor 来自 Parent.prototype。这会导致:
-
new Child()实例的constructor错误地显示为Parent -
instanceof虽仍正确(依赖__proto__链),但obj.constructor === Child判断失败 - 序列化、框架反射、开发工具中类型显示异常
修复方式只有一种推荐做法:显式赋值
Child.prototype = new Parent(); Child.prototype.constructor = Child; // 必须加这一行
避免直接赋值 prototype 对象
写成 Child.prototype = { method() {} } 会完全切断与 Parent.prototype 的联系,不仅丢失继承,还覆盖了默认的 constructor(此时它指向 Object)。应始终基于父类原型构建子类原型:
- 用
Object.create(Parent.prototype)替代new Parent(),更语义清晰,且不触发父类构造逻辑 - 若需兼容旧环境,可用
function F() {}中转,再设F.prototype = Parent.prototype
原型链末端需保持完整
子类原型链必须最终连到 Object.prototype,否则会丢失基础方法(如 toString、hasOwnProperty)。检查方式:
-
Child.prototype.__proto__ === Parent.prototype✔️ -
Parent.prototype.__proto__ === Object.prototype✔️ -
Object.prototype.__proto__ === null✔️(链终止)
若中间某环被意外重写(例如 Child.prototype.__proto__ = null),整条链断裂,继承失效。
ES6 class 不代表可忽略原型一致性
即使使用 class Child extends Parent,底层仍是原型链。Babel 或运行时仍会设置 Child.prototype.__proto__ = Parent.prototype,并自动修复 constructor。但若手动操作 Child.prototype(比如混入方法后未保留原有 __proto__),一致性仍会被破坏。建议:
- 优先用
extends语法,让引擎托管原型关系 - 若需动态增强原型,用
Object.setPrototypeOf(Child.prototype, Parent.prototype)显式维护链 - 避免直接改写
Child.prototype的整个值

















