Why does typeof only sometimes throw ReferenceError?

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

In Chrome and Firefox,

typeof foo

evalulates to \'undefined\'.

But

typeof (function() { return foo; })         


        
5条回答
  •  醉梦人生
    2020-12-18 23:55

    Digging through the spec, I think this all comes down to when the operator in question attempts to run GetValue() on its operand.

    typeof attempts to determine its operand's Type first. If that type is a Reference and is IsUnresolvableReference(), then it bails out and returns undefined. In essence, it does not fully evaluate the operand; if it did, anything that was undefined would throw an exception, so instead it short circuits and returns a nice, useful string.

    In the examples, self-executing functions and the addition operator call GetValue without first checking for IsUnresolvableReference() like typeof does: they call GetValue and throw an exception if the reference is unresolved (foo is undefined in our case). (I think! This is my best guess from reading through the spec.)

提交回复
热议问题