为什么我不能在try块中定义之前使用Javascript函数? [英] Why can't I use a Javascript function before its definition inside a try block?
问题描述
显示Hello world:
hello();
函数hello(){alert(Hello world); }
但是这会显示ReferenceError:hello is not defined:
try {
hello();
函数hello(){alert(Hello world); }
} catch(err){
alert(err);
$ b 因此,关于函数try块有一些特别的声明。有什么办法可以解决这个问题吗?
解决方案假设一个函数块建立一个带有前向函数引用的本地作用域,在一个直接函数的try块的内容似乎恢复了这种行为。
这个在Firefox,IE,Chrome中可用:
try {
(function(){
hello();
函数hello(){alert(Hello world); }
}())
} catch(err){
alert(err);
当然,在try函数中定义的函数和变量不再可见catch块,因为他们将没有立即函数包装。但这是try / catch脚本包装的一个可能的解决方法。
As discussed here, function definitions can be used before they're defined. But as soon as a section of code is wrapped in a try block, this ceases to be the case.
This displays "Hello world":
hello();
function hello() { alert("Hello world"); }
But this displays "ReferenceError: hello is not defined":
try {
hello();
function hello() { alert("Hello world"); }
} catch (err) {
alert(err);
}
So there is clearly something "special" about a try block with respect to function declarations. Is there any way to get around this behavior?
解决方案 Given that a function block establishes a local scope with forward function referencing, wrapping the contents of the try block in an immediate function seems to restore that behavior.
This works in Firefox, IE, Chrome:
try {
(function(){
hello();
function hello() { alert("Hello world"); }
}())
} catch (err) {
alert(err);
}
Of course functions and variables defined within the try-function are no longer visible in the catch block, as they would be without the immediate function wrapper. But this is a possible workaround for try/catch script wrapping.
这篇关于为什么我不能在try块中定义之前使用Javascript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!