JavaScript 中原型对象中 constructor 怎么修复
通过重新指定原型对象的 constructor 属性指向正确的构造函数即可修复。在 javascript 中,如果直接替换原型对象(例如 child.prototype = parent.prototype),会导致子类的 constructor 丢失或指向父类,此时只需手动将 child.prototype.constructor 重置为 child 即可恢复其身份标识。

直接赋值原型导致的 constructor 错误
当子类直接继承父类原型时,constructor 会指向父类构造函数,导致实例的构造函数类型判断出错。这是因为原型链上的 constructor 默认指向创建该原型的函数,而直接赋值并未改变这一事实。

function Parent() {}
function Child() {}
// 错误的继承方式:直接赋值原型
Child.prototype = Parent.prototype;
const child = new Child();
console.log(child.constructor === Parent); // true, 错误!应该是 Child
console.log(child.constructor === Child); // false
使用 Object.create 修复 constructor
使用 Object.create() 创建新原型对象并手动设置 constructor 是标准的修复方案。这种方式既保留了原型链的正确性,又确保了 constructor 属性准确指向当前构造函数,避免了直接赋值带来的副作用。

function Parent() {}
function Child() {}
// 正确的继承方式:使用 Object.create
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child; // 修复 constructor
const child = new Child();
console.log(child.constructor === Parent); // false
console.log(child.constructor === Child); // true, 正确!
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











