A.S.:问题是关于错误的类型,而不是关于现象
"use strict"
如果 NaN
和 undefined
等系统变量发生更改,则会抛出 TypeError。
但为什么是类型错误呢?为什么不是语法错误?
编辑:实际上,这里不是 SyntaxError,因为代码段的语法没有错误。
但错误的根源在于,某些 protected 对象无法手动更改;所以,很可能是访问错误(我知道没有这样的错误)。
那么,为什么访问错误看起来像类型错误?
最佳答案
在 ES5 中,有 6 种不同的 native errors :
-
This exception is not currently used within this specification. This object remains for compatibility with previous editions of this specification.
-
Indicates a numeric value has exceeded the allowable range.
-
Indicate that an invalid reference value has been detected.
-
Indicates that a parsing error has occurred.
-
Indicates the actual type of an operand is different than the expected type.
-
Indicates that one of the global URI handling functions was used in a way that is incompatible with its definition.
在您的情况下,抛出错误是因为您试图为 window.NaN
赋值或 window.undefined
,这是不可写的属性。
在分配新值之前,内部 [[Put]]方法检查 [[CanPut]] ,这将返回 false,因为该属性是不可枚举的。因此 [[Put]] 将抛出。
所以问题是分配的引用(assignment expression 中的左操作数)的可写性不是预期的。然后,在上面的 6 种错误中,最合适的似乎是 TypeError,即使可写性不完全是 type。 .
关于javascript - 为什么分配给 `NaN` 或 `undefined` 会导致 TypeError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37103330/