What's the best way to create a JavaScript namespace?
I have not yet found a common way on the Internet for creating a namespace in JavaScript.
What's the best way to create a namespace (and please list any downfalls that particular approach might have).
(function() {
var usefulVariable;
var foo = {
bar:function(){ alert('hi') }
};
// leak into global namespace
window.foo = foo;
})();
只有foo
暴露于全局名称空间,并且它“存在于”执行匿名函数名称空间的私有自执行程序中。
In JavaScript, namespaces can only be achieved through object literals, which can be as simple as this:
var MyNS = {
f1: function() {...},
f2: function() {...}
};
As others have attempted to show, if you want to provide a private scope within your namespace (which is suggested), the following method is the most appropriate:
var MyNS = (function() {
var private1 = "...",
private2 = "...";
return {
f1: function() {...},
f2: function() {...}
}
})();
The book Pro JavaScript Design Patterns (Harmes & Diaz, 2008) provides examples of namespace creation using simple object literals or self-executing anonymous functions, both of which are illustrated in Justin Johnson's excellent answer, and these approaches work well.
Depending on the situation, it might be possible that the namespace already exists and contains members. In such a case, these approaches would destroy any members in the namespace. If this is a concern, one can use an approach similar to this to preserve any existing members, while adding new ones:
var myNamespace = (function(ns) {
ns.f1 = function() { ... };
ns.f2 = function() { ... };
return ns;
})(window.myNamespace || {});
Here, myNamespace is assigned the value returned by the anonymous, self-executing function that receives the parameter ns. As one can see, the value of this parameter is either window.myNamespace or an empty object, depending on whether or not myNamespace has been previously declared.
链接地址: http://www.djcxy.com/p/17070.html