Can anyone explain the difference in behaviour between Internet Explorer and Firefox in regards to the 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 inside my namespace function by using either myFunction() or exposed.myFunction().
Outside my namepsace function I can use myNamespace.myFunction()
In Firefox, the results are the same with the exception of the bare named function call which does not work.
Should it work? If it shouldn’t, then why not?
If it should then is this a known bug?
To prevent false information:
IE has a problem with named function expressions which is what you have. The name of the function should only be available inside the function. From the specification:
where FunctionExpression is defined as:
But in IE, instead of making the name only available inside the function, it creates two different function objects, one assigned to the variable and the other to the name you gave the function. The following will yield
falsein IE (and throw an error in other browsers):It’s a known bug and if you have to code for (older versions of) IE, you better avoid named function expressions.
Related question: