Javascript: inconsistency when assigning a named function to a variable (named function expression)

Can anyone explain the difference in behavior between Internet Explorer and Firefox with respect to below:

var myNamespace = (function () {
  var exposed = {};

  exposed.myFunction = function myFunction () {
    return "Works!";
  }

  console.log(myFunction()); 
  // IE: "Works!"
  // Firefox: ReferenceError: myFunction is not defined

  console.log(exposed.myFunction());
  // IE: "Works!"
  // FF: "Works!"

  return exposed;
})();

console.log(myNamespace.myFunction()); 
// IE: "Works!"
// FF: "Works!"

In Internet Explorer, this method allows me to call my function from within my namespace function with myFunction()or exposed.myFunction().

Outside of my name function, I can use myNamespace.myFunction()

In Firefox, the results are the same except for calling a voice named function that does not work.

Should it work? If this is not so, then why?

If so, is this a known mistake?

+5
source share
3 answers

To prevent false information:

IE named function, . . :

Function FunctionExpression FunctionBody, . , FunctionDeclaration, Function Expression.

FunctionExpression :

:
    function opt( FormalParameterList opt) { FunctionBody }

IE , , , , - , . false IE ( ):

exposed.myFunction === myFunction;

, ( ) IE, .


:

+6

:

exposed.myFunction = function myFunction () {
    return "Works!";
}

(- : ) , -, (. ). exposed, :

exposed.myFunction = function() {
    return "Works!";
}

, , exposed, :

function myFunction () {
    return "Works!";
}

exposed.myFunction = myFunction;

(exposed.myFunction === myFunction) === true;

, console.log(myNamespace.myFunction()); console.log(exposed.myFunction());, myNamespace exposed.

+2

,

exposed.myFunction = function() {}

exposed myFunction.

myNamespace.

exposed.myFunction = function myFunction() {}

myNamespace, exposed.

0

All Articles