Home  >  Article  >  Web Front-end  >  Some thoughts on JavaScript namespaces_javascript tips

Some thoughts on JavaScript namespaces_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:45:301669browse

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

Copy code The code is as follows:
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,
Copy code The code is as follows:
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:
Copy code The code is as follows:
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:

Copy code The code 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 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

Copy code The code is as follows:

if (!window.ns) {
window.ns = {};
}
var ns;
if( typeof ns == "undefined"){
ns = {};
}
if(typeof ns.ClassName == "undefined"){
ns.ClassName = {};
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn