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