A few tips on JavaScript namespaces
- 2020-03-30 03:17:08
- OfStack
Recently, refactoring things, encounter namespace Settings, search some knowledge, consult some masters, write down their own experience
I'm sure you all know that window is top-level, so I'm not going to write window here, so I'm going to ignore it
1: about the top level
var ns = ns || {};
As you can see, if the Object is not found, it automatically creates a new Object(); If so, use the object directly so that it is not overwritten.
2: the second level Of course, you can also create a second level under the top-level ns, namely
ns.ModuleClass = {};
As you can see, a class is created under ns, and of course you can continue to create methods in the class, which is this:
ns.ModuleClass.method1= function() {////};
3: multistage So what do I do, like this com.qw.view, I want to set it to a namespace, so I'm going to set the namespace for each of the separated names, for each of the objects
Let's look at an example of setting it under window:
function namespace(sSpace) {
var arr = sSpace.split('.'),i = 0,nameI;
var root = window;
for (; nameI = arr[i++];) {
if (!root[nameI]) {
root[nameI] = {};
}
root = root[nameI];
}
return root;
}
And you can see that this is really the idea that I talked about above, which is to use a traversal, to set all the separated objects as objects, so that each separated object can be used separately.
4. Make a list of commonly used ones
, a quick and easy way to set up a namespace
if (!window.ns) {
window.ns = {};
}
var ns;
if(typeof ns == "undefined"){
ns = {};
}
if(typeof ns.ClassName == "undefined"){
ns.ClassName = {};
}