我有一个收到错误的用户

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
CheckObjectCoerciblesection 9.10中定义



我们可以在表15中看到TypeErrorundefined值被抛出了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)进行了测试。

07-24 17:01
查看更多