Firefox 以不同的方式解释函数语句,显然它们破坏了函数声明的声明提升。 (关于命名函数/声明与表达式的好读物 http://kangax.github.com/nfe/ )
为什么Firefox对语句的解释不同是因为以下代码:
if ( true ) {
function test(){alert("YAY");}
} else {
function test(){alert("FAIL");}
}
test(); // should alert FAIL
由于声明提升,函数test
应始终警告“失败”,但在 Firefox 中则不然。上面的代码实际上在 Firefox 中发出“YAY”警报,我怀疑导致这种情况发生的代码最终完全破坏了声明提升。
我假设当函数声明位于 if/else 或 try/catch 语句中时,Firefox 将函数声明转换为 var 声明。就像这样:
// firefox interpretted code
var test; // hoisted
if (true) {
test = function(){alert("yay")}
} else {
test = function(){alert("fail")}
}
在与 Šime Vidas 进行了简短的辩论之后,我不得不说 Firefox 对函数声明的处理是不标准的,因为:
生产 SourceElement :
语句针对函数进行处理
声明不采取任何行动.
生产 SourceElement : 声明
评价如下:
- 评估声明。
- 返回结果(1)。
FunctionDeclaration 和 Statement 都是 SourceElements,因此,语句内不应该有 FunctionDeclarations(if/else、try/catch)。给 Šime Vidas 一块布朗尼!
Try/catch 基本上是 if/else 的另一种形式,并且可能使用相同的异常代码。