代码是:
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'而不是给出错误。
答案 0 :(得分:3)
typeof
有一个不可解析的引用的特例;如果引用无法解析,它会显式返回undefined
。
typeof运算符具有不可解析引用的特殊情况:
11.4.3运营商类型
生产 UnaryExpression :
typeof
UnaryExpression 评估如下:
- 让 val 成为评估 UnaryExpression 的结果。
- 如果Type( val )是Reference,那么
- 如果IsUnresolvableReference( val )为
true
,请返回“undefined
”。- 让 val 成为GetValue( val )。
- 根据表20返回由Type( val )确定的字符串。
醇>
另一方面,在javascript中无处不在的内部GetValue(V)
函数(包括用于检索变量的值)如果引用不可解析则抛出ReferenceError:
8.7.1 GetValue(V)
- 如果Type( V )不是Reference,则返回 V 。
- 让base成为调用GetBase( V )的结果。
- 如果IsUnresolvableReference( V ),则抛出
ReferenceError
例外。- 如果IsPropertyReference( V ),则为 [...]
醇>
请参阅the spec。
答案 1 :(得分:2)
someVariable
被声明为not initialized
。但notDeclared
未声明..
someVariable
不包含任何默认值。但notDeclared
不可用。
答案 2 :(得分:1)
当我'警告(typeof 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。
此致