The JavaScript x () function {..} is considered as var x = function () {..} inside the `if 'in Firefox, and not in Chrome and Opera

Consider the following JavaScript code:

(function(){
  foo();
  function foo(){ alert('Hello, World!'); }
})();

In Firefox, Opera, and Chrome, this behaves as expected; we get a warning. Now in contrast:

(function(){
  if (true){
    foo();
    function foo(){ alert('Hello, World!'); }
  }
})();

Firefox 3.6 and 4 (beta) (i.e. SpiderMonkey for both) throws an exception: foo is undefined

Chrome (i.e.V8) and Opera (i.e. any Opera engine) work as expected (for me).

What is the right behavior, or is it left for implementation to solve?

FWIW, re-enable it in the function, and again it's good to return to FF:

(function(){
  if (true){
    (function(){
      foo();
      function foo(){ alert('Hello, World!'); }
    })();
  }
})();
+3
source share
4 answers

According to the ECMA-262 5th Edition specification , it SourceElementis defined as:

SourceElement :
Statement 
FunctionDeclaration

, FunctionDeclaration Statement . (, if) Statement s:

Block :
   { StatementList opt }

StatementList :
   Statement
   StatementList  Statement

, no FunctionDeclarations if s, , . , comp.lang.javascript, Mozzila " " . 16 ECMA-262, 3 5. Spidermonkey FunctionStatement. JScript FunctionDeclaration, JScript JScriptFunction. , .

FunctionStatement:

try {
  function Fze(b,a){return b.unselectable=a}
  /*...*/
} catch(e) { _DumpException(e) }

FunctionExpression:

var Fze;
try {
  Fze = function(b,a){return b.unselectable=a};
  /*...*/
} catch(e) { _DumpException(e) }

FunctionDeclaration:

function aa(b,a){return b.unselectable=a}
+2

, symantec. . foo, . .

+1

foo , if. if . , , Chrome .. , FF , .

, - .

+1

, :

var foo = function() {alert ('Hello, World!'); } Foo();

inside (function () {}) () you will get true private methods.

0
source

All Articles