0

不知何故,这样做会让人感觉有些不对或很脏,但它似乎比使用导出或窗口更具语义性。这个可以吗?

(function(global){
  var foo,bar;
  foo = 'Private Var';
  global.bar = 'Hello World';
})(window);
4

3 回答 3

2

您只是通过这样做为 window 创建别名,而不是替换它。我喜欢这种风格。“全球”使您的意图更加清晰。

于 2012-11-12T19:51:25.753 回答
2

你的模式很好。不过考虑一下:

// global code

(function () {

    var root = this;

    // use root variable to refer to the global object

}).call( this );

这种模式不依赖于"window"名称,这使得它具有可移植性。(当然,这个名字"root"是任意的。)

于 2012-11-12T19:54:41.727 回答
0

正如其他人所说,您并没有替换window您只是为它创建了一个别名。
你的模式很好,但我想提一点建议:如果你在全局上下文中运行 IIFE,你应该this作为global参数而不是 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.

于 2013-01-06T11:23:56.517 回答