JavaScript:instanceof运算符

时间:2013-01-28 18:01:50

标签: javascript prototype

第一个代码:

function MyConstructor() {}
var myobject = new MyConstructor();
MyConstructor.prototype = {};

[ myobject instanceof MyConstructor,   // false - why?
myobject.constructor == MyConstructor, // true
myobject instanceof Object ]           // true

即使替换了MyConstructor.prototype myobject仍然继承了Myconstructor.prototype的属性。那么为什么myobject instanceOf Myconstuctor是假的?

function MyConstructor() {}
MyConstructor.prototype = {};
var myobject = new MyConstructor();
myobject instanceof MyConstructor  // true (it is because myobject still inherits from
                                   // Myconstructor.prototype although it has been replaced)

第二

 function MyConstructor() {}
 MyConstructor.prototype = {};
 var myobject = new MyConstructor();

 myobject.constructor == MyConstructor;  // false (accepted )

因此,如果myobject.constructor是Object,为什么第一个:示例没有指向它,myobject.constructor如何在第一个示例中MyConstructor更改后仍然指向Myconstructor.prototype

你能澄清一下吗?

1 个答案:

答案 0 :(得分:3)

  

即使替换了MyConstructor.prototype,myobject仍会继承Myconstructor.prototype中的属性。

没有。它继承自被替换的旧对象。由于该对象为!== MyConstructor.prototypeinstanceof operator将产生错误。在第二个示例中,myobject继承了新原型(当前MyConstructor.prototype),这就是instanceof告诉您的内容。

  

所以如果myobject.constructor

constructor属性与instanceof完全无关。

function Constructor() {}
var oldProto = Constructor.prototype;
var oldInstance = new Constructor();

Constructor.prototype = {constructor:"something else"};
var newProto = Constructor.prototype;
var newInstance = new Constructor();

// all these are true:
Object.getPrototypeOf(oldInstance) === oldProto;
Object.getPrototypeOf(newInstance) == newProto;
oldProto !== newProto;
oldProto.constructor === Constructor; // was set implicitly on creating the function
oldInstance.constructor === oldProto.constructor; // inherited
newProto.constructor === "something else"; // if not explicitly set, comes from Object.prototype
newInstance.constructor === newProto.constructor; // inherited

Constructor.prototype === newProto;
newInstance instanceof Constructor; // because the above

Constructor.prototype !== oldProto;
! (oldInstance instanceof Constructor) // because the above