In order to avoid overwriting and conflicts between variables, a namespace can be generated. The namespace is a special prefix, which is implemented through {} objects in js.
In different anonymous functions, a different namespace is declared according to the function. The properties of the GLOBAL object in each anonymous function are not directly hung on GLOBAL, but are hung in the namespace of the sub-anonymous function, such as:
The code copy 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=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 further expanded to generate a secondary namespace:
The code copy 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>
Since generating namespaces is a very common function, the function of generating namespaces can be further defined as a function for easy calling, as follows:
The code copy 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>
Calling the namespace specific operation:
The code copy is as follows:
<script type="text/javascript">
//=============================================================
// Function A
// Engineer A
// 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;
})();
Similarly, whether it is direct team development with multiple people or indirect teamwork with individuals, good maintainability is required.
1. Add necessary code comments
2. Keep JS from conflicting, avoid the proliferation of global variables and use namespace reasonably