Firefox:函数提升错误 [英] Firefox: function hoisting error

查看:41
本文介绍了Firefox:函数提升错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经以为函数总是被提升到任何JavaScript代码块的顶部.

I used to assume that functions always get hoisted to the top of any block of JavaScript code.

例如,这有效:

document.addEventListener('something', dummy);
function dummy(){
    console.log('dummy');
}

,但这不起作用,在Firefox中抛出ReferenceError,但在Chrome中起作用:

but this doesn't work and throws ReferenceError in Firefox, but works in Chrome:

if(document){        
    document.addEventListener('something', dummy1);
    function dummy1(){
        console.log('dummy');
    }
}

小提琴代码

最初,我认为Chrome在测试之前也会抛出错误,但是以某种方式可以正常工作.有人可以解释为什么它在Firefox中不起作用吗?

Fiddle code

Initially, I assumed that Chrome would also throw an error before I tested, but somehow it works correctly. Can someone explain why it doesn't work in Firefox?

推荐答案

看来这已经有一段时间了-这是2011年的参考资料:

It appears this has been an issue for quite a while - here's a reference from 2011: http://statichtml.com/2011/spidermonkey-function-hoisting.html

很显然,Firefox会很高兴地在一个块的外部声明函数声明,但不会在一个块的内部这样做.链接文章的作者认为这(虽然出乎意料)符合

Apparently Firefox will happily hoist function declarations OUTSIDE of a block, but doesn't do so INSIDE a block. The author of the linked article argues this is (while unexpected) compliant with the ECMA-262 spec, which only allows statements inside of a block...as a function declaration is not a statement. However, I'll note that Firefox happily allows function declarations inside of a block - it merely refuses to hoist them.

这篇关于Firefox:函数提升错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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