讨论 here , 函数定义可以在定义之前使用。但是一旦一段代码被包裹在一个 try block 中,情况就不再是这样了。
这会显示“Hello world”:
hello();
function hello() { alert("Hello world"); }
但这会显示“ReferenceError: hello is not defined”:
try {
hello();
function hello() { alert("Hello world"); }
} catch (err) {
alert(err);
}
因此,在函数声明方面,try block 显然有一些“特殊”之处。有什么办法可以避免这种行为?
最佳答案
Firefox 以不同方式解释函数语句,显然它们破坏了函数声明的声明提升。 ( A good read about named functions / declaration vs expression )
为什么 Firefox 对语句的解释不同是因为下面的代码:
if ( true ) {
function test(){alert("YAY");}
} else {
function test(){alert("FAIL");}
}
test(); // should alert FAIL
由于声明提升,函数 test
应该总是提示“失败”,但在 Firefox 中不是。上面的代码实际上在 Firefox 中警告“YAY”,我怀疑导致这种情况发生的代码最终完全破坏了声明提升。
我假设 Firefox 将位于 if/else 或 try/catch 语句中的函数声明转换为 var 声明。像这样:
// firefox interpretted code
var test; // hoisted
if (true) {
test = function(){alert("yay")}
} else {
test = function(){alert("fail")}
}
在与 Šime Vidas 的简短辩论之后,我不得不说 Firefox 处理函数声明的方式是非标准的,因为:
The production SourceElement : Statement is processed for function declarations by taking no action.
The production SourceElement : Statement is evaluated as follows:
- Evaluate Statement.
- Return Result(1).
FunctionDeclaration 和 Statement 都是 SourceElements,因此,语句(if/else,try/catch)中不应该有 FunctionDeclarations。给 Šime Vidas 一 block 巧克力蛋糕!
Try/catch 基本上是 if/else 的另一种形式,可能使用相同的异常代码。
关于javascript - 为什么我不能在 try block 中定义之前使用 Javascript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4069100/