【发布时间】:2015-12-27 18:32:57
【问题描述】:
我很困惑为什么在将对象的构造函数属性更改为指向另一个函数之后,该对象仍然是旧构造函数的实例
//Original Constructor
function orig_cons() {}
//New Constructor
function new_cons(){}
//Adding property to myfun prototype
new_cons.prototype.x = 1;
//Invoking a new object of 1st constructor
var obj1 = new orig_cons();
//check obj1 instanceof 1st constructor
console.log(obj1 instanceof orig_cons); // true
//Changing constructor property to point to 2nd function
obj1.constructor = new_cons;
//check obj1 instanceof 2nd function
console.log(obj1 instanceof new_cons); // false
而且obj1的prototype属性还是原来构造函数的prototype:
console.log(Object.getPrototypeOf(obj1)); //orig_cons {}
【问题讨论】:
-
constructor属性与instanceof的工作方式无关。 -
创建后更改构造函数时原型链没有变化,对象原型仍然相同。
-
清理你的代码片段 -
myfun与那里的任何东西有什么关系?并使用内联代码 sn-p