'typeof'运算符在这里讲的是什么?

时间:2013-05-24 09:19:48

标签: javascript typeof

代码是:

 var someVariable;    // this variable is declared but not initialised...

 alert(typeof someVariable);   // alerts 'undefined'
 alert(typeof notDeclared);    // also alerts 'undefined' irrespective 
                               //  of the fact it has not been declared..

看起来有点令人困惑。现在,如果我做了

alert(someVariable);    // again alerts 'undefined'
alert(notDeclared);     // causes an error

jsFiddle链接:http://jsfiddle.net/gjYZt/2/

如果'typeof notDeclared'未定义,那么当我提醒'notDeclared'时,它也应警告'undefined'而不是给出错误。

4 个答案:

答案 0 :(得分:3)

简答:

typeof有一个不可解析的引用的特例;如果引用无法解析,它会显式返回undefined

答案很长:

typeof运算符具有不可解析引用的特殊情况:

  

11.4.3运营商类型

     

生产 UnaryExpression typeof UnaryExpression 评估如下:

     
      
  1. val 成为评估 UnaryExpression 的结果。
  2.   
  3. 如果Type( val )是Reference,那么   
        
    1. 如果IsUnresolvableReference( val )为true,请返回“undefined”。
    2.   
    3. val 成为GetValue( val )。
    4.   
  4.   
  5. 根据表20返回由Type( val )确定的字符串。
  6.   

另一方面,在javascript中无处不在的内部GetValue(V)函数(包括用于检索变量的值)如果引用不可解析则抛出ReferenceError:

  

8.7.1 GetValue(V)

     
      
  1. 如果Type( V )不是Reference,则返回 V
  2.   
  3. 让base成为调用GetBase( V )的结果。
  4.   
  5. 如果IsUnresolvableReference( V ),则抛出ReferenceError例外。
  6.   
  7. 如果IsPropertyReference( V ),则为   [...]
  8.   

请参阅the spec

答案 1 :(得分:2)

someVariable被声明为not initialized。但notDeclared未声明..

someVariable不包含任何默认值。但notDeclared不可用。

答案 2 :(得分:1)

  

当我'警告(ty​​peof notDeclared);'时,那也应该给出一个   错误。不是吗?

不,因为the specification is clear如果typeof的操作数无法解析,typeof的结果必须为undefined(请参阅2a)。

当您尝试在示例中评估不可解析的表达式(例如notDeclared)时,会出现ReferenceError - 这也是根据规范。

答案 3 :(得分:0)

运算符typeof返回操作数的类型。

此列表总结了typeof

的可能返回值
Type    Result  
Undefined   "undefined"   
Null    "object"  
Boolean "boolean"  
Number  "number"  
String  "string"  
Host object (provided by the JS environment)    Implementation-dependent  
Function object (implements [[Call]] in ECMA-262 terms) "function"  
E4X XML object  "xml"  
E4X XMLList object  "xml"    
Any other object    "object"  

如果你警告返回undefined那是因为你的变量类型是unifined。

此致