我很困惑为什么在更改对象的构造函数属性以指向另一个函数之后,对象仍然是旧构造函数的实例
//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属性仍然是原始构造函数的原型:
console.log(Object.getPrototypeOf(obj1)); //orig_cons {}
答案 0 :(得分:0)
instanceof检查对象的原型而不是构造函数,举个例子:
function Person(name){
this.name = name;
}
var p = new Person();
console.log(p instanceof Person); //true
function Func(){}
p.constructor = Func;
console.log(p instanceof Person); // true
Person.prototype = {};
console.log(p instanceof Person); // false
注意更改原型如何影响instanceof
。
来自MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof
instanceof运算符测试了constructor.prototype的存在 对象的原型链。