What is pollution--------> global variables is pollution. Common ways to solve pollution A. Function B. Object C. namespace D. Immediate function
The function and object is that we put the variable into a function or object, become a local variable, by accessing the variables within the function to obtain the desired content, this is not explained in detail.
Here is an example of a namespace: this access will greatly reduce the pollution problem.
/* Top level * /var demo={};//root /* Level two * /demo.web={sum:10, tab:function () {} }; Demo.finance = { sum:20, tab:function () {} }; /* Level three */ Demo.web.default = { sum:30 }; Demo.web.product = { sum:40 }; Demo.web.account = {}; /* How to use * /Console.log (demo.web.sum); Console.log (demo.finance.sum); Console.log (demo.web.default.sum); Console.log (demo.web.product.sum);
Here is the immediate function: that is, the definition and invocation of the same, do not need to call to execute, immediately after the function must be a semicolon, otherwise immediately after the function will be wrong.
(function () { var sum = 1; Console.log (sum); 1 }) (); (function () { var sum = 2; Console.log (sum); 2 }) (); Console.log (sum); Sum is not defined
However, access to certain variables in the immediate function is not accessible, and the variables in the immediate function are usually accessed in the following three ways. The first window, the second global variable form, and the third return form.
Window mode:
(function (w) { var sum = ten; W.sum = sum; }) (window); Console.log (sum); 10 The sum is a global variable at this time
If you want to access the values in multiple immediate functions, then the above method will be out of order, resulting in a lot of pollution
The following solutions: JSON
(function (w) { var sum=10; JSON = { sum:sum, fn:function () { Console.log ("FN"); } } w.$ = JSON; }) (window); $.fn (); fn Console.log ($.sum); 10
Solving global variable pollution problems