一个未定义的变量怎么会抛出类型错误?

How could an undefined variable throw a type error?

本文关键字:怎么会 类型 错误 变量 一个 未定义      更新时间:2023-09-26

我有一个用户得到错误

TypeError: a is undefined

我不明白这是怎么发生的。访问未定义的变量不会抛出引用错误吗?在什么情况下会抛出类型错误?

正如@jgillich在他的回答中指出的那样,以下代码在undefined对象上生成TypeError

> a
ReferenceError: a is not defined
> var a;
> a.x
TypeError: a is undefined
要理解其中的原因,我们可以参考ECMAScript 5.1规范11.2.1 Property Accessors。我们对步骤5感兴趣

5。调用CheckObjectCoercible ( baseValue )。

在我们的示例中,baseValue是引用a的值。即baseValueundefined

CheckObjectCoercible定义在章节9.10

抽象操作CheckObjectCoercible如果其参数是不能使用ToObject转换为Object的值,则抛出错误。它由表15定义:

我们可以在表15中看到,对于undefinednull值,会抛出一个TypeError

所以我们有TypeError而不是ReferenceError的原因,像往常一样,因为规范是这样说的!

还有其他方法可以在undefined上获得TypeError,值得注意的是,ToObject也会为undefined抛出TypeError

这三行代码产生了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)进行测试的。

> a
ReferenceError: a is not defined
> var a;
> a.x
TypeError: a is undefined