Encapsulation: The advantage of using object encapsulation is that you can reduce the chance of global variable contamination by speaking of properties, functions are subordinate to an object.
Before encapsulation:
<Script> varname="Foo"; //name is global and is exposedI=1; //globally, the variables declared without the VAR keyword are global and have little to do with location functionShow () {//Show is global, exposedConsole.log ("name->"+name); Console.log (++i); }//I is the Global 2Show (); //3Show ();</Script>
Operation Result:
After encapsulation:
Only exposed bar, using closure package var bar=function () { var i=1; return{ Name: "Bar", show:function () { console.log ("name->" +this.name); Console.log (++i); };}; var bar1=bar (); 2 bar1.show (); 3 bar1.show (); var bar2=bar (); 2, because it is encapsulated, and the closure, I is the local private bar2.show ();
Operation Result:
javascript--Package