我有一个收到错误的用户
TypeError: a is undefined
我很困惑这怎么发生。不会尝试访问未定义的变量引发参考错误吗?在什么情况下会引发类型错误?
正如@jgillich在回答中指出的那样,以下代码TypeError
在undefined
对象上产生一个。
> a
ReferenceError: a is not defined
> var a;
> a.x
TypeError: a is undefined
要了解原因,请参阅ECMAScript 5.1规范的第11.2.1节“属性访问器”。我们对第5步感兴趣
5.调用CheckObjectCoercible(baseValue)。
在我们的示例中,baseValue是reference的值a
。这意味着baseValue是undefined
。
CheckObjectCoercible
在9.10节中定义
如果抽象操作CheckObjectCoercible的参数是无法使用ToObject转换为Object的值,则会引发错误。由表15定义:
我们可以在表15中看到,一个TypeError
被抛出undefined
和null
值。
因此,像往常一样,我们之所以使用aTypeError
而不是a的原因ReferenceError
是,因为规格说明是如此!
还有其他方法可以获取TypeError
on undefined
,特别是ToObject也可以抛出TypeError
for undefined
。
这三行代码产生TypeError: can't convert undefined to object
:
Object.defineProperties({}, undefined);
Object.prototype.toLocaleString.call(undefined);
Object.prototype.valueOf.call(undefined);
尽管这次消息更清晰了。
也直接在undefined
产品上调用TypeError: undefined has no properties
undefined.foo();
undefined.x;
所有这些都使用Firefox 33.0a2(Aurora)进行了测试。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句