gpt4 book ai didi

javascript - 为什么 getPrototypeOf 'null' 会出错?

转载 作者:行者123 更新时间:2023-11-28 18:05:04 25 4
gpt4 key购买 nike

所以我知道“null”是一种“对象”

但是,当我执行 Object.getProtoTypeOf(null) 时,我收到错误。 instanceof 也是如此,这有点相同。

如果 null 是一种 Object 类型...它应该在它的原型(prototype)链中,对吧?

// 'object'
typeof null;

// gives error - Cannot convert undefined or null to object
Object.getPrototypeOf(null);

// false ---- why?
null instanceof Object

是我漏掉了什么,还是 JS 太嬉皮了?!

最佳答案

看,null 不是一个对象。确实,typeof null 的计算结果为 'object',但它实际上来自 JavaScript 的一个限制,并且可能被认为是一个怪癖 - 在某种程度上是一个错误。引用this article :

The "typeof null" bug is a remnant from the first version of JavaScript. In this version, values were stored in 32 bit units, which consisted of a small type tag (1–3 bits) and the actual data of the value. The type tags were stored in the lower bits of the units. There were five of them:

  • 000: object. The data is a reference to an object.
  • 1: int. The data is a 31 bit signed integer.
  • 010: double. The data is a reference to a double floating point number.
  • 100: string. The data is a reference to a string.
  • 110: boolean. The data is a boolean.

That is, the lowest bit was either one, then the type tag was only one bit long. Or it was zero, then the type tag was three bits in length, providing two additional bits, for four types. Two values were special:

  • undefined (JSVAL_VOID) was the integer −230 (a number outside the integer range).
  • null (JSVAL_NULL) was the machine code NULL pointer. Or: an object type tag plus a reference that is zero.

It should now be obvious why typeof thought that null was an object: it examined its type tag and the type tag said “object”.

现在,对于其余操作,null 被视为原始值。这就是为什么,例如,null instanceof Object 返回 false - 任何基元都会返回 false,因为它不能是实例。将 42 instanceof Number (false) 与 typeof 42 === 'number' 进行比较。

<小时/>

对于Object.getPrototypeOf(null),它有点不同。在 ES5 standard如果该函数的参数是原语 - 任何原语,则该函数应该抛出异常:

When the getPrototypeOf function is called with argument O, the following steps are taken:

  • If Type(O) is not Object throw a TypeError exception.
  • Return the value of the [[Prototype]] internal property of O.

但是,在 ES2015 中,它们 changed it :

When the getPrototypeOf function is called with argument O, the following steps are taken:

  • Let obj be ToObject(O).
  • ReturnIfAbrupt(obj).
  • Return obj.[[GetPrototypeOf]]().

...所以 Object.getPrototypeOf(42) 现在可以工作了。然而 Object.getPrototypeOf(undefined)Object.getPrototypeOf(null) 都会抛出相同的错误:

Uncaught TypeError: Cannot convert undefined or null to object

此异常是由 ToObject() 方法 ( doc ) 引发的 - 这是有道理的,因为不能“装箱” nullundefined。在某些方面,它与尝试访问 nullundefined 属性时遇到的错误类似。

关于javascript - 为什么 getPrototypeOf 'null' 会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42855464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com