Which JS function-declaration syntax is correct according to the standard?

前端 未结 5 481
走了就别回头了
走了就别回头了 2020-12-10 03:39
  var foo = function(){ return 1; };
  if (true) {
    function foo(){ return 2; }
  }
  foo(); // 1 in Chrome // 2 in FF
  //I just want to be sure, is FF 4 not \"s         


        
5条回答
  •  悲哀的现实
    2020-12-10 04:03

    Both are technically wrong, according to the ECMAScript standard, because function declarations are only allowed at the top level or directly inside other functions. Technically a function declaration inside an if block is a syntax error. Most implementations allow it as in extension, but they interpret it differently.

    The reason for the difference is that Chrome is treating the foo "declaration" as a normal function declaration and hoisting it to the beginning of the scope. Firefox (for historical reasons IIRC) only declares the function when the if statement gets executed.

    To better demonstrate the difference, you could try running this similar code:

    console.log(foo()); // 2 in Chrome, error in FF
    
    var foo = function(){ return 1; };
    console.log(foo()); // 1 in both Chrome and FF
    
    if (true) {
        function foo(){ return 2; }
    }
    console.log(foo()); // 1 in Chrome // 2 in FF
    

    Edit: Your second example is exactly the same. JavaScript doesn't have block scope, only function-level and program-level. The "problem" isn't that the function declaration is in a block, it's that it's not a top-level statement.

提交回复
热议问题