3

So I know polluting the global namespace referencing the window is a bad thing, especially if you have multiple 3rd party references. So this would be not desirable:

window.someObject = someObject;

That will reference it everywhere. What if I instead use it like this?

var MyApplication = window.MyApplication;
MyApplication.someObject = someObject;

Of course using this approach requires referencing MyApplication = window.MyApplication at the top of each module that needs access to this created namespace. So back to my question. Is this an acceptable approach to giving global access without polluting the window global namespace?

4

2 回答 2

1

如果你想要全局访问,你需要有某种全局的。这是常见的做法。

来自jQuery 源代码的示例:

_jQuery = window.jQuery,
_$ = window.$,

我相信所有的大框架都是这样做的。我认为用一个容器变量污染全局命名空间是完全可以接受的。

于 2013-07-25T01:40:00.460 回答
0

您还可以(在全球范围内):

(function(lib) {

  // in here, lib references window.MyApplication
  ...

}(MyApplication));

因此您可以轻松更改传入的对象。

于 2013-07-25T02:22:51.047 回答