作为讨论在这里,在定义前,他们可以用函数定义.但是只要一段代码被包装在try块中,就不再是这种情况了.
这显示"Hello world":
hello();
function hello() { alert("Hello world"); }
Run Code Online (Sandbox Code Playgroud)
但是这会显示"ReferenceError:hello is not defined":
try {
hello();
function hello() { alert("Hello world"); }
} catch (err) {
alert(err);
}
Run Code Online (Sandbox Code Playgroud)
因此,关于函数声明的try块显然有一些"特殊".有没有办法绕过这种行为?
为什么以下代码在Chrome和Firefox之间输出不同的结果?
f = function() {return true;};
g = function() {return false;};
(function() {
if (g() && [] == ![]) {
f = function f() {return false;};
function g() {return true;}
}
})();
console.log(f());
Run Code Online (Sandbox Code Playgroud)
在Chrome中:结果是false.但是,在Firefox中,它是true.
以上代码的关键行是第4行,根据我对函数名称提升的了解,该函数g应该在第6行,即第2行被第6行覆盖.IMO,Chrome的行为是正确的.
我对吗?如果是这样,为什么Firefox输出不同的结果?
在Chrome和Firefox中运行此功能会给出不同的答案:
(function() {
if(true) {
function f() { alert("yes"); };
} else {
function f() { alert("no"); };
}
f();
})();
Run Code Online (Sandbox Code Playgroud)
在Chrome中,结果是'不'在Firefox中,结果为'是'
为什么不同?