Recently refactoring things, encountered the setting of namespaces, searched some knowledge, consulted some experts, write down their own experience
I believe you all know, window is the top, here is not to write window, first ignore
1: About the top
Copy Code code as follows:
As you can see, if you find this object, you automatically create the new object (), and if so, use the object directly so that it is not overwritten.
2: Second level, and of course you can create a second level under the top NS, that
Copy Code code as follows:
You can see that a class is created under the NS, and of course you can continue to create a method in the class, which is this:
Copy Code code as follows:
Ns. moduleclass.method1= function () {////};
3: MultilevelWhat should be done, such as this com.qw.view, I want to make him a namespace, it is necessary for each point separated by the name of the separate namespace, set to object
Let's look at an example and set him under window:
Copy Code code 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 really the thought I said above, with a traversal, the separation of all objects, so that each separate can be used alone.
4: make a list of common, simple and quick tips for setting up namespaces
Copy Code code as follows:
if (!WINDOW.NS) {
Window.ns = {};
}
var ns;
if (typeof ns = "undefined") {
ns = {};
}
if (typeof ns. ClassName = = "undefined") {
Ns. ClassName = {};
}