Why does typeof only sometimes throw ReferenceError?

后端 未结 5 1115
臣服心动
臣服心动 2020-12-18 23:41

In Chrome and Firefox,

typeof foo

evalulates to \'undefined\'.

But

typeof (function() { return foo; })         


        
5条回答
  •  梦毁少年i
    2020-12-19 00:04

    This is standard behavior. The typeof operator almost takes a reference of the next variable you pass to it.

    So let's try typeof foo.

    The javascript interpreter looks at typeof and finds the type of foo.

    Now we try typeof (function() { return foo })()

    The javascript interpreter looks at typeof. Since the expression afterwards isn't a variable, it evaluates the expression. (function() { return foo })() throws a ReferenceError because foo is undefined. If it were possible to pass the reference of a varialbe i.e. something like (function() { return *foo })() then this wouldn't happen.

    Note: According to this, one may think that typeof (foo) would throw an error, since (foo) isn't a variable and must be evaluated, but that is incorrect; typeof (foo) will also return "undefined" if foo isn't defined.

    Essentially, the interpreter evaluates the next variable, but not expression, in a "safe" context so that typeof doesn't throw an error.

    It is a bit confusing.

提交回复
热议问题