JS namespace How to play a detailed

Source: Internet
Author: User

1. Why first use the JS namespace

in our project, if more than one person writes JS for the same page, a naming conflict can occur, if all functions are global, as follows:

In A.js

function com () {...}

In B.js

function com () {...}

and a page refers to the two JS files, so that when we call a problem, we may always call the function in the first file, I was in a project before I ran into this problem, I myself b.js the name of the AJAX response function in the file and the Ajax response function name in the A.js file, as a result, the AJAX response data goes to a a.js each time, and the two response functions do not have the same function, so there is a problem, then we are the b.js of the AJAX response function name renamed, and later There was no conflict, (at the time I didn't know how to use the command space, so I used this method)

In fact, if I make a namespace, so that a.js inside the function in a space, b.js inside the function in the B command space.

This allows us to invoke the following calls:

A.com (); B.Com ();

2.js How to create namespaces

We know a lot of languages that natively support namespaces, such as C++,java, and so on, but our JavaScript does not have rules in its syntax that specifically provide syntax for namespaces, but if we are familiar with the notation of JS object literals, We can completely understand the JS namespace play. ( in fact, it is the use of JS object literal syntax to implement JS namespace )

Let's introduce the play of the S-namespace, or the above-mentioned question above, to implement the following call:

A.com (); B.Com ();

You can use the following methods:

var a={com:function () () {...}} var b={com:function () {}}

Above are the method of using object literal, defined two objects A and object B is global, and two objects have a COM method, no variables, (we know that JS inside the object can have properties and methods), can see we have implemented JS command space.

For example: The login interface has a login.js file with the following namespace:

        var   BP={                login:{                        //the rest of the functions and global variables on this login page are written in this, that is, inside the namespace                    }                                               } 

This means that the global object BP has a login object, and then the operation of the login interface is in the properties and methods are placed in the login object, that is, the operation of this page in the namespace Bp.login inside. BP is the name of the project, loging that the function of this JS

A lot of people may not be used to this way, compared to the habit such as bp.login this way to register a command space Namespace.register ("bp.login") (compared to other languages of the command space); we only need to dynamically create the BP object and the BP sub-object login in the Resister function.

Dynamic creation of objects we can achieve 2.eval by using two methods: 1.window objects.

we only introduce by registering the window method

We know that defining an object can be so, window[' BP ']={}; Window. bp[' login ']={}; Indicates that the window object has a child object BP,BP has a child object login.

The following is the method used to dynamically split the string, and then use the method above to dynamically create the object's

var nameSpace = NameSpace | | {};(function () {var global = window;/** * * @param {} Nsstr * @return {} */NAMESPACE.NS = function (nsstr) {var parts = Nsstr.split ("."), root = global,max,i;for (i = 0, max = parts.length; i < Max; i++) {//If not present, create an attribute if (typeof Root[pa Rts[i]] = = = "undefined") {Root[parts[i]] = {};} root = Root[parts[i]];} return root;};}) ();

Explain it individually.

A. Indicates that namespace is defined as an object

var nameSpace = NameSpace | | {};

b.//Anonymous functions

(function () {

Code, running codes

})();

Note: () There are two meanings in javascript: The first is the operator, and the second is the delimiter.

The above anonymous function needs to explain two points:

① Red parentheses are an anonymous function, and the red brackets represent a split, indicating that the function inside is a part;

② Green brackets denote an operator that indicates that the function inside the red parenthesis is to run, and that it runs directly after defining an anonymous function.

3. Using namespaces

In our login interface of the Login.js file, we generally hope that each of our JS file inside the code is placed in their own namespace, so that there is no naming conflict between the multiple JS files

The contents of the Login.js file are as follows:

NAMESPACE.NS ("Bp.login"); Register command Space bp.login={min_height:660,//page Minimum Height min_widht:1024,//page minimum width isie:false, init:function () {This.isi       E=$.browser.msie;       This.regevent ();       This.initpage (); BP.page.i18nInit ();//internationalization of loading} .....}

Use the functions inside the namespace:

The contents of the Utils.js file are as follows:

NAMESPACE.NS ("Bp.utils"); bp.utils = {    time:3000,    timeout:null,     interValForFake:null,    isProgressBarShow:false,     Timeoutreturn: ",     alert:function (content) {         var dom=$ ("#alert_tip");         $ (". Alert_tip_content", DOM) . text (content);         if (Dom.hasclass ("ALERT_TIP_SYSTEM_CONFIG_BG")) {             var tbw=$ ("#tb") in System settings. Width ();             var left=tbw/2 -dom.width ()/ 2 +180;            $ ("#alert_tip"). CSS ({"Left ": Left," Top ":         }else{      &});nbsp;     var bw=$ ("Body"). Width ();             var left=bw/2 -dom.width ()/2;             $ ("#alert_tip"). CSS ("left" and left);         }        dom.show ();         this.timeoutreturn = settimeout (function () {             dom.fadeout (+);         },2000);  &NBSP;&NBSP;&NBSP;},&NBSP;&NBSP;&NBSP;&NBSP, ....... ............... }

In short, the following is no longer listed, anyway, every JS file has a command space of their own, and then called when the name of the namespace can be!

JS namespace How to play a detailed

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.