Some tips on JavaScript namespaces _javascript

Source: Internet
Author: User

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:
var ns = NS | | {};

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:
Ns. Moduleclass = {};

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 = {};
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.