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

前端 未结 5 480
走了就别回头了
走了就别回头了 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:11

    fiddle. This is Undefined Behaviour. It's a mess.

    How firefox interprets it is handled by the other answers

    How chrome interprets it

    var foo = function() { return 1 };
    if (true) {
        function foo() {
            return 2;
        }
    }
    console.log(foo());
    

    What's acctually happening is function foo is being declared then overwritten with a local variable foo immediately.

    This gets translated into

    function foo() {
        return 2;
    }
    var foo;
    foo = function() { return 1 };
    if (true) { }
    console.log(foo());
    

提交回复
热议问题