Javascript Hoisting in Chrome And Firefox

前端 未结 3 545
悲哀的现实
悲哀的现实 2020-12-28 20:52

Running this in Chrome and Firefox gives different answers:

(function() {

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


        
3条回答
  •  天命终不由人
    2020-12-28 21:32

    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.

提交回复
热议问题