Pergunta

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);
Foi útil?

Solução

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

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top