Why are function declarations handled differently in different browsers?

前端 未结 2 1542
一个人的身影
一个人的身影 2020-11-30 14:40

Although I couldn\'t find a reference to this easily in google, I\'m familiar with the fact that, in javascript, global function declarations get interpreted before any code

相关标签:
2条回答
  • 2020-11-30 14:55

    Function declarations are not valid in blocks. You have undefined behaviour which is undefined.

    Function declarations at a top level (either global or top level within a function) are hoisted.

    Function declarations inside blocks are a syntax error in strict mode

    (function () { 
      "use strict"; 
      if (true) { 
        function g() { } 
      } 
    })();
    

    SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function.

    0 讨论(0)
  • 2020-11-30 15:14

    The ECMA standard for this behavior is to throw a SyntaxError when parsing the script. Unfortunately doing that is not compatible with the web as Raynos says.

    See Which JS function-declaration syntax is correct according to the standard? for some extended discussion on the issue.

    0 讨论(0)
提交回复
热议问题