我有一个收到错误的用户
TypeError: a is undefined
我很困惑这怎么发生。不会尝试访问 undefined variable 引发引用错误吗?在什么情况下会引发类型错误?
最佳答案
正如@jgillich在回答中指出的那样,以下代码在TypeError
对象上生成了undefined
。
> a
ReferenceError: a is not defined
> var a;
> a.x
TypeError: a is undefined
要了解原因,请参阅ECMAScript 5.1规范部分11.2.1 Property Accessors。我们对第5步感兴趣
在我们的示例中,baseValue是引用
a
的值。这意味着baseValue是undefined
。CheckObjectCoercible
在section 9.10中定义我们可以在表15中看到
TypeError
和undefined
值被抛出了null
。因此,像往常一样,我们之所以使用
TypeError
而不是ReferenceError
的原因是,因为规范如此说明!还有其他方法可以在
TypeError
上获取undefined
,尤其是ToObject还会为TypeError
抛出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)进行了测试。