To avoid overwrites and conflicts between variables, you can generate a namespace. a namespace is a special prefix, which is implemented through the {} object in js.
In different anonymous functions, a different namespace is declared based on the function. The attributes of the GLOBAL Object in each anonymous function are not directly attached to the GLOBAL function, instead, it is stored in the namespace of the sub-Anonymous function, for example:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var GLOBAL = {}
</Script>
<Script type = "text/javascript">
(Function (){
Var a = 123, a1 = 256;
GLOBAL. A = {}
GLOBAL. A. str =;
})();
</Script>
<Script type = "text/javascript">
(Function (){
Var b1 = 123, b2 = 256;
GLOBAL. B = {}
GLOBAL. B. str =;
})();
</Script>
If the program in the same anonymous function is very complex and has many variable names, the namespace can be further expanded to generate a second-level namespace:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var GLOBAL = {}
</Script>
<Script type = "text/javascript">
(Function (){
Var a = 123, a1 = 256;
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 namespace generation is a very common function, you can further define the namespace generation function as a function for convenient calling, as shown below:
Copy codeThe Code is 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 call a namespace, perform the following operations:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
// ================================================ ======================================
// Function
// Engineer
// E-mail: ctkl68945@gmail.com msn: ctkl68945@hotmail.com"
// 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 =;
GLOBAL. A. str1 = a1;
})();
Similarly, no matter the direct team development of multiple people or the indirect team cooperation of individuals, good maintainability is required.
1. Add necessary code comments
2. Prevent JS conflicts. Avoid the proliferation of global variables and properly use namespaces.