简体   繁体   English

我应该如何封装我的库?

[英]How should I encapsulate my library?

I am going to go with this possibly 我可能会去

var my_lib = 
  {
  /*
  my_code
  */
  }

as a way to not clutter the global name space. 作为一种不会使全局名称空间混乱的方式。 Is this OK? 这个可以吗?

(function (global) {
 /* my code */

 global["someName"] = someObject;

})(window);

That's fine, however var will limit its scope. 很好,但是var将限制其范围。 You might also want to wrap it in a closure as well. 您可能还希望将其包装在一个闭合中。

There are different ways to accomplish it. 有不同的方法来完成它。 I ran into this article by kangax in the past: http://perfectionkills.com/unnecessarily-comprehensive-look-into-a-rather-insignificant-issue-of-global-objects-creation/ 过去,我是kangax遇到的这篇文章: http ://perfectionkills.com/unnecessarily-comprehensive-look-into-a-rather-insignificant-issue-of-global-objects-creation/

which walks you through different approaches. 引导您完成不同的方法。 I think this is the best article on the topic. 我认为这是有关该主题的最佳文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM