The namespace in JS

Source: Internet
Author: User

Try not to use global variables to prevent environmental pollution and naming conflicts.

Therefore, it is a good solution to put global variables under a namespace.

Statically named spaces

1. Direct Assignment

This is the most basic method, but it is very verbose, you have to write multiple variable names repeatedly. The advantage is that it is safe and does not create ambiguity.

1 varMYAPP = {}2  3Myapp.id =0;4  5Myapp.next =function () {6     returnmyapp.id++; 7 }8  9Myapp.reset =function () {TenMyapp.id =0;  One } A   -Window.console &&Console.log ( - Myapp.next (), the Myapp.next (), - Myapp.reset (), - Myapp.next () -);//0, 1, undefined, 0

You can use this in the namespace function to refer to the object, but consider that the function is reassigned and this will point to the unknown.

1 varMYAPP = {}2  3Myapp.id =0;4  5Myapp.next =function () {6     return  This. id++; 7 }8  9Myapp.reset =function () {Ten      This. ID =0;  One } A   -Myapp.next ();//0 -Myapp.next ();//1 the varGetnextid =Myapp.next; -Getnextid ();//NaN whoops! 


2. Using the object literal method

It would be convenient to change the name of the namespace, as compared to the above method. However, it is still important to note that there is a risk of using this.

1 varMYAPP = {2  3Id:0,4  5 next:function () {6         return  This. id++; 7     },8  9 reset:function () {Ten          This. ID =0;  One     } A } -Window.console &&Console.log ( - Myapp.next (), the Myapp.next (), - Myapp.reset (), - Myapp.next () -)//0, 1, undefined, 0


3. Module mode

The advantage of module mode is that it saves the global variable in a function wrapper (A-function wrapper) that executes immediately, and the function wrapper returns an object equivalent to the public interface of the module. Also, a variable that does not return in the function wrapper will be a private variable, visible only to the public function that references it.

1 varMYAPP =(function () {2  3     varId=0;4  5     return {6 next:function () {7             returnid++; 8         },9  Ten reset:function () { OneID =0;  A         } -     };  - })();  the   -Window.console &&Console.log ( - Myapp.next (), - Myapp.next (), + Myapp.reset (), - Myapp.next () +)//0, 1, undefined, 0

As with the object literal method above, the namespace name here can be easily modified as well. But the object literal method is inflexible-it is all about the definition of a property, it cannot support logical writing, and all attributes must be initialized and values between attributes cannot be easily passed to another property by reference (so, for example, internal closures are not possible). Module mode does not have the above limitation, and also has the characteristics of protecting private variables.

Dynamic namespaces

We can also call namespace injection. The namespace is represented by proxy, and the proxy points directly to the inside of the function wrapper-which means that we no longer need to bind a return to the namespace. This makes the definition of the namespace more flexible. Dynamic namespaces have all the benefits of module naming patterns and are more intuitive and easy to read than module schemas.

4. Apply a namespace parameter supply a Namespace Argument

Here we simply pass the namespace as a variable to the function we execute. The variable ID is a private face, because it is not defined to the context variable.

1 varMYAPP = {};2 (function (context) {3     varID =0;4  5Context.next =function () {6         returnid++; 7     };8  9Context.reset =function () {TenID =0;  One     } A }) (MYAPP);  -   -Window.console &&Console.log ( the Myapp.next (), - Myapp.next (), - Myapp.reset (), - Myapp.next () +)//0, 1, undefined, 0

We can even set the context as a global object (as long as you change a word!). )

1 varMYAPP = {};2 (function (context) {3     varID =0;4  5Context.next =function () {6         returnid++; 7     };8  9Context.reset =function () {TenID =0;  One     } A})( This);  -   -Window.console &&Console.log ( the next (), - next (), - Reset (), - Next () +)//0, 1, undefined, 0


5. Use the This keyword as the namespace proxy (a Namespace proxy)

The advantage of using the This keyword as a namespace is that the This keyword is static in the given execution environment and does not change by chance.

1 varMYAPP = {};2 (function () {3     varID =0;4  5      This. Next =function () {6         returnid++; 7     };8  9      This. reset =function () {TenID =0;  One     } A }). Apply (MYAPP);  -   -Window.console &&Console.log ( the Myapp.next (), - Myapp.next (), - Myapp.reset (), - Myapp.next () +);//0, 1, undefined, 0

Because the Apply and call functions bind this and the specified function object, the above (function () {...}). Apply (namespace), the this in the anonymous function must point to the namespace.

The following explains the function of the apply and call functions to perform an environment binding:

1 varSubsys1 = {}, Subsys2 = {};2 varNextidmod =function (startid) {3     varid = Startid | |0;4  5      This. Next =function () {6         returnid++; 7     };8  9      This. reset =function () {TenID =0;  One     } A }; -   - Nextidmod.call (SUBSYS1);  theNextidmod.call (Subsys2, +);  -   -Window.console &&Console.log ( - Subsys1.next (), + Subsys1.next (), - Subsys2.next (), + Subsys1.reset (), A Subsys2.next (), at Subsys1.next () -)//0, 1, undefined, 1001, 0

Of course, want to bind with the global environment, super simple .....

1 nextidmod ();    2  3 window.console && console.log (4    Next (),5     Next (),6    Reset (),7    next ()8// 0, 1, undefined, 0

The biggest advantage of using apply and call is that you can use whatever environment object you want to bind.

Other considerations:

I don't use inline namespaces because they're hard to track, and they make your code bloated. The complex embedded namespaces are very much in line with the nostalgic Java code that likes the packaging chain (package chains).

JS has no official namespace concept, so you can create your own solution as you wish.

Original link: https://javascriptweblog.wordpress.com/2010/12/07/namespacing-in-javascript/

The namespace in JS

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.