Question

Somehow something feels wrong or dirty by doing this, but it seems to be more semantic than using exports or window. Is this ok?

(function(global){
  var foo,bar;
  foo = 'Private Var';
  global.bar = 'Hello World';
})(window);
Was it helpful?

Solution

Your pattern is fine. Consider this, though:

// global code

(function () {

    var root = this;

    // use root variable to refer to the global object

}).call( this );

This pattern does not rely on the "window" name, which makes it portable. (The name "root" is, of course, arbitrary.)

OTHER TIPS

You're just creating an alias for window by doing this, not replacing it. I like the style. 'global' makes your intention much clearer.

As others said, you aren't replacing the window, you're just creating an alias for it.
Your pattern is good, but I want to make a little suggestion : if you're running that IIFE in the global context, you should pass this as the global argument and not window :

(function(global){

})(this);  

This helps your code to be more cross-platform, say if you would make a module that runs in the browser but runs on another platform too (say like nodejs or rhino) where the window object doesn't exist, or it isn't the global object that youwant it to be.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top