在Chrome和Firefox中使用JavaScript [英] Javascript Hoisting in Chrome And Firefox

查看:119
本文介绍了在Chrome和Firefox中使用JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

$ p code $(function(){

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

})();

在Chrome中,结果为'no'
在Firefox中,结果为'yes' / p>

为什么区别?

解决方案

标准,所以不要那样做。这是一个已知的问题。您可以使用函数表达式来代替声明:

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

着名Kangax关于函数表达式的文章给出了一些额外的细节:
$ b


FunctionDeclarations 只允许出现在 FunctionBody 。在语法上,它们不能出现在 Block ({...})中,例如 if while for 语句。这是因为 Blocks 只能包含 Statements ,而不是 SourceElements FunctionDeclaration 是。 $ b

同样的文章还说:


值得一提的是,根据规范,实现允许引入语法扩展(请参阅第16节),但仍然完全符合。这正是现在这么多客户所发生的事情。他们中的一些人将块中的函数声明解释为任何其他函数声明 - 只需将它们提升到封闭范围的顶部;其他 - 引入不同的语义,并遵循稍微复杂的规则。



Running this in Chrome and Firefox gives different answers:

(function() {

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

    })();

In Chrome the result is 'no' In Firefox the result is 'yes'

Why the difference?

解决方案

Declaring functions inside conditional statements is non-standard, so do not do that. That's a known issue. You may use function expressions instead of the declarations:

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

The famous Kangax article on function expressions gives some additional details:

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.

The same article also says:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆