How does typeof circumvent the ReferenceError when

2020-02-06 04:01发布

foo; // ReferenceError: foo is not defined

typeof(foo); // undefined

How does typeof circumvent the ReferenceError when supplied an undeclared variable identifier? Is this just JavaScript interpreter "magic" or can it be explained in terms of user-land concepts?

标签: javascript
1条回答
劳资没心,怎么记你
2楼-- · 2020-02-06 05:02

No, this cannot be explained in user-land concepts - it's "magic" if you want.

EcmaScript uses the Reference specification type to explain cases like this. These references are used to describe the semantics of assignments, method calls, eval and many more. Typically, the GetValue algorithm is called on them to dereference them (e.g. in the evaluation of your expression statement), and this does throw the ReferenceError when the reference is not resolvable.

The typeof operator in contrast does not just do GetValue, but has a special case to handle these undeclared-variable references:

  1. If Type(val) is Reference, then

    a. If IsUnresolvableReference(val) is true, return "undefined".

查看更多
登录 后发表回答