2

代码是:

 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

4 回答 4

3

简短的回答:

typeof对不可解析的引用有特殊情况;undefined如果引用不可解析,它会显式返回。

长答案:

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

11.4.3 typeof 运算符

产生式 UnaryExpression : typeof UnaryExpression的评估如下:

  1. val为计算UnaryExpression的结果。
  2. 如果 Type( val ) 是 Reference,那么
    1. 如果 IsUnresolvableReference( val ) 是true,则返回 " undefined"。
    2. val为 GetValue( val )。
  3. 根据表 20返回由 Type( val ) 确定的字符串。

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

8.7.1 获取值(V)

  1. 如果 Type( V ) 不是引用,则返回V
  2. 设 base 为调用 GetBase( V ) 的结果。
  3. 如果 IsUnresolvableReference( V ),则抛出ReferenceError异常。
  4. 如果 IsPropertyReference( V ),那么
    [...]

请参阅规范

于 2013-05-24T09:24:32.300 回答
2

someVariable已声明not initializednotDeclared但未声明..

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

于 2013-05-24T09:22:46.950 回答
1

当我执行 'alert(typeof notDeclared);' 时,这也应该给出一个错误。不是吗?

不,因为规范很明确,如果 to 的操作数typeof不可解析,则 的结果typeof必须是undefined(查看 2a)。

当您尝试评估无法解析的表达式时,例如notDeclared在您的示例中,您会得到一个 ReferenceError - 这也符合规范。

于 2013-05-24T09:23:15.680 回答
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"  

如果您的警报返回未定义,那是因为您的变量类型未定义。

问候

于 2013-05-24T09:25:39.350 回答