Recently refactoring things, I came across namespace settings, searched for some knowledge, consulted some experts, and wrote down my own experience
I believe everyone knows that window is top-notch, so I won’t write about window here. Okay, ignore
1: About the top-level
var ns = ns || {};
As you can see, in fact, if it is found that there is no such object, new Object() will be automatically created; if there is, this object will be used directly, so It won't be covered.
2: The second level, of course, you can also create the second level under the top-level ns, that is,
ns.ModuleClass = {};
As you can see, a class is created under ns. Of course, you can also continue to create methods in the class, that is This is this:
ns.ModuleClass.method1= function() {/ ///};
3: How to do multi-level , such as this com.qw.view, I want to set it as a namespace, this requires each A dot-separated name is used to set the namespace separately, and it is set to the object
. Let’s look at an example and set 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;
}
You can see that it is indeed the idea I mentioned above, using a traversal to set all the separated objects as objects, so that each separated object can be used independently.
4: List the commonly used and some tips for setting up namespace simply and quickly
if (!window.ns) {
window.ns = {};
}
var ns;
if( typeof ns == "undefined"){
ns = {};
}
if(typeof ns.ClassName == "undefined"){
ns.ClassName = {};
}