第一个代码:
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
。
你能澄清一下吗?
答案 0 :(得分:3)
即使替换了MyConstructor.prototype,myobject仍会继承Myconstructor.prototype中的属性。
没有。它继承自被替换的旧对象。由于该对象为!== MyConstructor.prototype
,instanceof
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