Search code examples
javascriptiife

Is this ok to replace window with global in an IIFE?


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);

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.)