1

第一个代码:

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在第一个示例中发生了变化。

你能澄清一下吗?

4

1 回答 1

4

即使 MyConstructor.prototype 被替换,myobject 仍然从 Myconstructor.prototype 继承属性。

不,它继承自被替换的旧对象。并且由于该对象是!== MyConstructor.prototype,因此instanceof运算符将产生错误。在您的第二个示例中,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
于 2013-01-28T18:09:23.993 回答