1

I'm trying to understand the following scenario where I have defined a function in one scope and want to access it another.

I have two different JavaScript files, helper.js and main.js, and both have a self-invoking function:

helper.js:

var outerShowData;

(function(){
    var innerShowData = function(param1, param2){
        alert("Data : "+ param1 +" - "+ param2);
    }

    outerShowData = innerShowData;
})();

main.js:

(function(){
    outerShowData("alpha", "beta");
    outerShowData("gamma", "theta");
})();

If I first include the helper.js in my page and then the main.js, this works perfectly in Firefox, Safari and Google Chrome. However it doesn't work in IE8.

Could anyone point out what am I doing wrong here?

I wrote the self-invoking function just not to dirty up the global scope. Any help in this direction would greatly help me.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • Works fine for me in IE8. Could you make a [jsFiddle](http://jsfiddle.net/) that reproduces the problem, please? – Ry- Aug 03 '12 at 20:34

1 Answers1

1
// Your code would work identically with or without this variable declaration
var outerShowData;

(function(){
    // This is a local variable, and cannot be accessed outside the containing function()
    var innerShowData = function(param1, param2){
        alert("Data : "+ param1 +" - "+ param2);
    }

    // This assigns a value to a global variable
    outerShowData = innerShowData;
})();

Your outerShowData variable is global. It can be accessed by any other piece of code in any JavaScript environment that isn't broken. If this code is giving you problems with IE8, it appears that IE8 is broken, thought it's more likely that your problem lies elsewhere in your code. It would be a fundamental problem for IE8 to not support global variables properly.

You can try setting and calling window.outerShowData instead, which explicitly creates a global variable.

I wrote the self-invoking function just not to dirty up the global scope.

This is kind of silly. You're "dirtying" the global scope either way, except now you're doing it with a bunch of unnecessary code and indirection.

user229044
  • 232,980
  • 40
  • 330
  • 338