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);
有帮助吗?

解决方案

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top