JavaScript: instanceof operator
First code:
function MyConstructor() {}
var myobject = new MyConstructor();
MyConstructor.prototype = {};
[ myobject instanceof MyConstructor, // false - why?
myobject.constructor == MyConstructor, // true
myobject instanceof Object ] // true
even though MyConstructor.prototype
is replaced myobject
still inherits the properties from Myconstructor.prototype
. So why is myobject instanceOf Myconstuctor
false?
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)
second:
function MyConstructor() {}
MyConstructor.prototype = {};
var myobject = new MyConstructor();
myobject.constructor == MyConstructor; // false (accepted )
So if myobject.constructor is Object why the first: example not pointing it, how can the myobject.constructor
still points to MyConstructor
since Myconstructor.prototype
has changed in first example.
Can you clarify this please?
Solution 1:
even though MyConstructor.prototype is replaced myobject still inherits the properties from Myconstructor.prototype.
No. It inherits from the old object which was replaced. And since that object is !== MyConstructor.prototype
, the instanceof
operator will yield false. In your second example, myobject
inherits from the new prototype (the current MyConstructor.prototype
), and that's what instanceof
tells you.
So if myobject.constructor
The constructor
property is completely unrelated to 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