为什么instanceof在原型改变后一直说true? [英] why instanceof keeps saying true after prototype changed?
问题描述
instanceof
操作符应该看原型,不是吗?为什么在对象的原型改变后它不改变它的答案?下面的例子:
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???
推荐答案
本案例说明 在 MDN 中 :
请注意,如果一个 instanceof 测试的值可以根据修改构造函数的prototype属性,不能通过改变对象原型而改变,因为改变了一个对象原型在标准 ECMAScript 中是不可能的.然而,可以使用非标准的 __proto__
伪属性
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
这将记录错误:
xx.constructor.prototype = new String('s');
console.log(xx instanceof MyKlass);
简而言之,您不应该尝试改变 JavaScript 对象,因为它们不是被设计为可变的.我不知道您的用例是什么,但可能有更好的解决方案,无论是组合、内部状态还是其他什么.
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.
这篇关于为什么instanceof在原型改变后一直说true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!