Why does typeof only sometimes throw ReferenceError?

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

In Chrome and Firefox,

typeof foo

evalulates to \'undefined\'.

But

typeof (function() { return foo; })         


        
5条回答
  •  清歌不尽
    2020-12-18 23:59

    The error "ReferenceError: foo is not defined" is not being thrown by typeof, its being thrown by the function itself. If you had used:

    typeof (function() { return 2; })()
    

    it would have returned "number" as expected, but in this example JavaScript is not even getting to the point where typeof is being run on anything. You are receiving the same error as if you had run:

    function test () {
        return foo;
    }
    test();
    

提交回复
热议问题