7Mar/110
关于typeof运算
在JavaScript中,变量可以不声明直接赋值使用,但不能直接引用,否则会出错,看下面代码:
console.log(foo); //reference error
if(foo){ //reference error
alert('true');
}
typeof(foo); //undefined
if(foo){ //reference error
alert('true');
}
typeof(foo); //undefined
看了上面代码对于进行typeof运算为什么不报错,而是返回undefined,这是因为typeof操作并不调用GetValue。ECMA中关于typeof操作的描述:
The production UnaryExpression : typeof UnaryExpression is evaluated as follows:
- Let val be the result of evaluating UnaryExpression
- If Type(val) is Reference, then
- If IsUnresolvableReference(val) is true, return "undefined"
- Let val be GetValue(val)
- Return a String determined by Type(val) according to Table
| typeof val | result |
| undefined | "undefined" |
| Null | "object" |
| Boolean | "boolean" |
| Number | "number" |
| String | "string" |
| Object (native and does not implement [[Call]]) | "object" |
| Object (native or host and does implement [[Call]]) | "function" |
| Object (host and does not implement [[Call]]) |
Implementation-defined except may not be "undefined", "boolean", "number", or "string". |