In order to avoid contamination of global variables, it can be privatized with the addition of namespaces and closure packages.
One, using namespaces
Change a variable to a private variable under a namespace
varmyapp={}; Myapp.namespace=function(name) {varParts=name.split ('. ')); varCurrent=MyApp; for(varIinchparts) { if(!Current[parts[i]]) {Current[parts[i]]={}; } Current=Current[parts[i]]; } }; Myapp.namespace (' Event '); Myapp.namespace (' Dom.style '); Console.dir (MYAPP);
The above is equivalent to
var myapp={ event:{}, dom:{ style:{}} ;
This defines the two properties event and Dom under the MyApp namespace.
Second, the use of closures
var user= (function () { var _name= ' ls ', _age=27; return { getuserinfo:function () { return _name+ ' _ ' +_age; } } }) (); Console.log (User.getuserinfo ());
The name and age attributes are encapsulated and cannot be accessed externally.
JavaScript Design Patterns and open practice Learning (iv) Private variables