In order to avoid overwriting and conflict between variables, namespaces can be generated, and namespaces are a special prefix, which is implemented through the {} object in JS.
In different anonymous functions, a different namespace is declared according to the function, and the properties of the global object in each anonymous function are not directly attached to the global, but are hung under the namespace of the secondary anonymous function, such as:
Copy Code code as follows:
<script type= "Text/javascript" >
var global={}
</script>
<script type= "Text/javascript" >
(function () {
var a=123, a1=256;
GLOBAL. a={}
GLOBAL. A.str=a;
})();
</script>
<script type= "Text/javascript" >
(function () {
var b1=123, b2=256;
GLOBAL. b={}
GLOBAL. B.str=a;
})();
</script>
If the program in the same anonymous function is very complex and has many variable names, the namespace can be extended further to generate a level two namespace:
Copy Code code 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 generating namespaces is a very common feature, you can further define the ability to generate namespaces as a function for easy invocation, as follows:
Copy Code code 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>
Invoke namespace specific actions:
Copy Code code as follows:
<script type= "Text/javascript" >
//=============================================================
Function A
Engineer Armour
Email: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=a;
GLOBAL. A.STR1=A1;
})();
Similarly, no matter how many people's direct team development, or personal indirect team cooperation, all need good maintainability.
1, add the necessary code comments
2, so that JS does not conflict, we need to avoid the proliferation of global variables, the rational use of namespaces