Recently, I reconstructed things and encountered the namespace settings. I searched for some knowledge, asked some experts, and wrote down my experience.
I believe everyone knows that window is top-notch, so I won’t write window here, so I will ignore it first
1: About the top
The code copy is as follows: var ns = ns || {};
It can be seen that if you find that there is no such object, you will automatically create new Object(); if there is, you will use this object directly, so that it will not be overwritten.
2: The second level , of course, you can also create the second level under the top level ns, that is,
The code copy is as follows: ns.ModuleClass = {};
You can see that a class is created under ns, and of course you can continue to create the methods in the class, that is, this is:
The code copy is as follows: ns.ModuleClass.method1= function() {////};
3: How to do multi-levels , such as com.qw.view. I want to set it into a namespace. This requires setting the namespace for each point-separated name and setting it into an object.
Let's look at an example and set it under window:
The code copy is as follows:
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 what I mentioned above. I used a traversal to set all the separated ones into objects, so that each separated one can be used separately.
4: List the commonly used , simple and quick tips for setting namespaces
The code copy is as follows:
if (!window.ns) {
window.ns = {};
}
var ns;
if(typeof ns == "undefined"){
ns = {};
}
if(typeof ns.ClassName == "undefined"){
ns.ClassName = {};
}