To avoid overwriting and collisions between variables, namespaces can be generated, and namespaces are a special prefix that is implemented in JS with {} objects.
In different anonymous functions, a different namespace is declared according to function, and the properties of the global object in each anonymous function are not directly attached to global, but are hung under the namespace of the secondary anonymous function, such as:
- < Script type="text/javascript">
- var GLOBAL={}
- </ Script >
- < Script type="text/javascript">
- (function () {
- var a=123, a1=N;
- GLOBAL. A={}
- GLOBAL. A.str=a;
- })();
- </ Script >
- < Script type="text/javascript">
- (function () {
- var b1=123, b2=N;
- GLOBAL. B={}
- GLOBAL. B.str=a;
- })();
- </ Script >
If the program in the same anonymous function is very complex, with many variable names, the namespace can be further extended to generate a level two namespace:
- < Script type="text/javascript">
- var GLOBAL={}
- </ Script >
- < Script type="text/javascript">
- (function () {
- var a=123, a1=N;
- GLOBAL. A={};
- GLOBAL. A.cat={};
- GLOBAL. A.dog={};
- GLOBAL. A.cat.name="Mini";
- GLOBAL. A.cat.move=function() {
- }
- GLOBAL. A.dog.name="Mini";
- GLOBAL. A.dog.move=function() {
- }
- })();
- </ Script >
Because building namespaces is a very common feature, you can further define the functionality that generates namespaces as a function for easy invocation, as follows:
- < Script type="text/javascript">
- var GLOBAL={}
- Global.namespace = function (str) {
- var arr=str. Split ("."), o=GLOBAL ;
- For (i=arr[0]== "GLOBAL"? 1:0;i<Arr.length ; i++) {
- O[arr[i]]=o[arr[i] | | {};
- o = o [Arr[i]];
- }
- }
- </ Script >
To invoke a namespace-specific action:
- < Script type="text/javascript">
- //=============================================================
- Function A
- Engineer Armor
- Email:[email protected] Msn:[email protected] "
- 2012-11-06
- //=============================================================
- (function () {
- var a=123, a1="Hello World";
- Global.namespace ("A.cat");
- Global.namespace ("A.dog");
- GLOBAL. A.cat.name="Mini";
- GLOBAL. A.cat.move=function() {
- }
- GLOBAL. A.dog.name="Mini";
- GLOBAL. A.dog.move=function() {
- }
- GLOBAL. A.str=a;
- GLOBAL. A.STR1=A1;
- })();
Similar in turn, no matter how many people direct team development, or personal indirect team work, need good maintainability.
1. Add the necessary code comments
2, let JS do not conflict, you need to avoid the flooding of global variables, reasonable use of namespaces