A simple method for defining JavaScript namespaces

Source: Internet
Author: User

The $. Extend method of jquery needs to be referenced in this method. Therefore, jquery needs to be referenced first. The version does not matter. You can write this method in the public module.

Source code:

<SCRIPT type = "text/JavaScript" src = "JS/jquery-1.7.2.min.js"> </SCRIPT>

// NS can be a string or a specified object // if it is defined for the first time, it must be used. the function creates the corresponding space function def_name_space (NS, OP) {Switch (typeof NS) {Case 'object': If (NS = NULL) throw new error ('Param error'); jquery. extend (NS, OP); break; Case 'string': var NSS = NS. split (". "); var part = Window; for (I in NSS) {var name = NSS [I]; If (! Part [name]) part [name] = new object (); Part = part [name];} jquery. extend (part, OP); break; default: Throw new error ('Param error'); break ;}}

Easy to use

    DEF_NAME_SPACE("zh",{        dotest:function(){            alert('zh.dotest');        }    });        DEF_NAME_SPACE("zh.mySpace",{        dotest:function(){            alert('zh.mySpace.dotest');        }    });

Of course, the difference is that this method is used to define the namespace. The content in the namespace should actually be a JSON expression.

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.