我在使用 JavaScript 时遇到了一些奇怪的行为
function Class() {};
var a = {};
a.__proto__ = Class.prototype
a instanceof Class => true
将 proto 设置为 null,然后重新为其分配相同的值会使 instanceof 运算符返回 false 而不是 true。
a.__proto__ = null
a.__proto__ = Class.prototype
a instanceof Class => false
最佳答案
我请您注意:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
Warning: Changing the [[Prototype]] of an object is, by the nature of how modern JavaScript engines optimize property accesses, a very slow operation, in every browser and JavaScript engine. The effects on performance of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in obj.proto = ... statement, but may extend to any code that has access to any object whose [[Prototype]] has been altered. If you care about performance you should avoid setting the [[Prototype]] of an object. Instead, create a new object with the desired [[Prototype]] using Object.create().
和
Warning: While Object.prototype.proto is supported today in most browsers, its existence and exact behavior has only been standardized in the ECMAScript 6 specification as a legacy feature to ensure compatibility for web browsers. For better support, it is recommended that only Object.getPrototypeOf() be used instead.
简而言之,你会破坏一些东西,然后问它们为什么会被破坏。 __proto__
不会被改变,并且没有标准化的行为,所以你不能依赖它做你想做的事情。
你想做什么?你的最终目标是什么?
关于javascript - 将 __proto__ 设置为 null,然后重新设置它会破坏 Javascript 中的 instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32940793/