The instanceof
operator should look at the prototype, no? Why does it not change its answer after the object's prototype has been changed? Example below:
// The .prototype of objects created with 'new MyKlass'
// is MyKlass.prototype
var MyKlass = function(name, age) {
this.name = name;
this.age = age;
}
var xx = new MyKlass('xx', 20);
console.log(xx instanceof MyKlass); // true, OK
xx.prototype = new String('s');
console.log(xx instanceof MyKlass); // also true, WHY???
This case is explained in the MDN :
Note that if the value of an instanceof test can change based on changes to the prototype property of constructors, it cannot be changed by changing an object prototype, because changing an object prototype is not possible in standard ECMAScript. It is however possible using the non-standard
__proto__
pseudo-property
This would log false :
xx.constructor.prototype = new String('s');
console.log(xx instanceof MyKlass);
In short, you shouldn't try to mutate JavaScript objects, they weren't designed to be mutable. I don't know what's your use case but there's probably a better solution, be it composition, internal state, or something's else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With