The use of namespaces to avoid js conflicts to avoid global variable flooding

  • 2020-03-30 03:21:05
  • OfStack

To avoid overrides and conflicts between variables, you can generate a namespace, which is a special prefix, in js, implemented by the {} object.

In different anonymous functions, a different namespace is declared according to the function. The properties of GLOBAL objects in each anonymous function are not directly hung on GLOBAL, but under the namespace of sub-anonymous functions, such as:
 
<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 extended to generate a second level namespace:
 
<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, you can further define the function of generating 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> 

Invoke namespace specific operation:
 
<script type="text/javascript"> 
//============================================================= 
//Features A
//Engineer a
// 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, both direct team development by multiple people and indirect team work by individuals require good maintainability.

1. Add the necessary code comments

2. To avoid JS conflicts, it is necessary to avoid the overflow of global variables and use namespaces reasonably

Related articles: