Child.prototype 指向 Parent 实例后,constructor 属性为何丢失
将子类的原型对象直接赋值为父类实例会导致其 constructor 属性指向父类构造函数。这是因为赋值操作覆盖了原型的默认结构,而新对象的 constructor 属性继承自父类实例的原型链。要解决这个问题,在赋值后手动将 constructor 重新指向子类构造函数即可恢复正确的指向关系。

function Parent() { this.name = 'parent'; } function Child() { this.type = 'child'; } // 错误做法:直接赋值导致 constructor 丢失 Child.prototype = new Parent(); console.log(Child.prototype.constructor === Parent); // true console.log(Child.prototype.constructor === Child); // false // 正确做法:修复 constructor Child.prototype = new Parent(); Child.prototype.constructor = Child; console.log(Child.prototype.constructor === Child); // true
上述代码展示了通过 new Parent() 创建实例并赋值给 Child.prototype 后的行为。此时 Child.prototype.constructor 实际上是指向 Parent 的。通过显式赋值 Child.prototype.constructor = Child,我们修正了该属性,使其重新指向子类自身。
使用 Object.create 替代 new 能否避免构造函数的副作用
使用 Object.create(Parent.prototype) 可以创建一个仅继承原型属性的空对象,从而避免执行父类构造函数带来的副作用。这种方式不会调用 Parent 中的初始化逻辑,适合不需要在原型链上保留实例属性的场景。但同样需要手动修复 constructor 属性以保持规范。

一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
function Parent() { this.name = 'parent'; } function Child() { this.type = 'child'; } // 使用 Object.create 避免执行 Parent 构造函数 Child.prototype = Object.create(Parent.prototype); // 必须修复 constructor Child.prototype.constructor = Child; const child = new Child(); console.log(child.name); // undefined console.log(child.type); // 'child' console.log(child instanceof Parent); // true console.log(child instanceof Child); // true
这段代码演示了 Object.create 的应用。由于没有调用 Parent 构造函数,child 实例中没有 name 属性。这种模式常用于纯原型继承,确保实例只拥有自己定义的属性。修复 constructor 依然是必要步骤,否则 instanceof 检查虽不受影响,但其他依赖 constructor 的逻辑可能会出错。
修复 constructor 后 instanceof 检查是否依然有效
修复 constructor 属性不会影响 instanceof 的检查结果,因为 instanceof 是基于原型链进行判断的。只要 Child.prototype 位于 Parent.prototype 的原型链上,instanceof 就会返回 true。修改 constructor 只是改变了原型对象上的一个属性值,并不改变原型链的结构。
function Parent() {} function Child() {} Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child; const obj = new Child(); console.log(obj instanceof Child); // true console.log(obj instanceof Parent); // true console.log(obj.constructor === Child); // true
运行结果显示,尽管 constructor 被手动修正为 Child,obj 依然能通过 instanceof 检查确认其属于 Parent 和 Child。这证明了 instanceof 机制与 constructor 属性是独立的。开发者可以放心地修复 constructor 以符合惯例,而不必担心破坏类型检查逻辑。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










