Why are feature declarations handled differently in different browsers?

Although I could not find a link to this easily on google, I am familiar with the fact that in javascript global function declarations are interpreted before any code is executed. In other words, this works great:

f();
function f() {}

However, I noticed that chrome and firefox have different interpretations of what a global function declaration is. In particular, chrome is happy to read a function declaration that is inside an if block in the first pass, but firefox is not.

try {document.write(f);}               // works in chrome
catch(e) {document.write(e.message);}  // throws an error in firefox

try {document.write(g);}               // works in chrome and firefox
catch(e) {document.write(e.message);}

if(true) function f() {}
function g() {}

You can try this example yourself with fiddle . I am using Chrome 16.0.912.75 and Firefox 9.0.1.

ECMA ? "" ? "" ( )? ?

+4
2

. undefined undefined.

( ).

​​

(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.

+11

ECMA SyntaxError script. , , .

. JS ? .

0

Source: https://habr.com/ru/post/1016194/


All Articles