javascript - 将 __proto__ 设置为 null,然后重新设置它会破坏 Javascript 中的 instanceof

标签 javascript prototype instanceof

我在使用 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/

相关文章:

Javascript cookie 持续时间

javascript - 鼠标悬停时的 Jssor 光标

JavaScript oop : Designing classes correctly

javascript - 如何告诉WebStorm解析继承的方法?

javascript - 为什么有些数组方法依赖于全局 Array 对象?

php - Laravel 5.5 $exception instanceof AuthenticationException 未按预期工作

java - 对象通用父类(super class) java instanceof

javascript - 如何在 d3 VERSION 4 中获取相对于元素原点的 (x, y) 坐标

javascript ->> 运算符/操作数/修饰符的作用是什么?

java - 避免在观察者方法中使用instanceOf