gpt4 book ai didi

Chrome 和 Firefox 中的 Javascript 提升

转载 作者:可可西里 更新时间:2023-11-01 02:19:00 25 4
gpt4 key购买 nike

在 Chrome 和 Firefox 中运行这个给出不同的答案:

(function() {

if(true) {
function f() { alert("yes"); };
} else {
function f() { alert("no"); };
}
f();

})();

在 Chrome 中,结果为“否”在 Firefox 中,结果为"is"

为什么不同?

最佳答案

在条件语句中声明函数是非标准的,所以不要那样做。这是一个已知问题。您可以使用函数表达式而不是声明:

var f;
if(true) {
f = function() { alert("yes"); };
} else {
f = function() { alert("no"); };
}
f();

famous Kangax article on function expressions提供一些额外的细节:

FunctionDeclarations are only allowed to appear in Program or FunctionBody. Syntactically, they can not appear in Block ({ ... }) — such as that of if, while or for statements. This is because Blocks can only contain Statements, not SourceElements, which FunctionDeclaration is.

同一篇文章还说:

It's worth mentioning that as per specification, implementations are allowed to introduce syntax extensions (see section 16), yet still be fully conforming. This is exactly what happens in so many clients these days. Some of them interpret function declarations in blocks as any other function declarations — simply hoisting them to the top of the enclosing scope; Others — introduce different semantics and follow slightly more complex rules.

关于Chrome 和 Firefox 中的 Javascript 提升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14242399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com