In the normal development, there are always some ways we can be useful in different places, so we will encapsulate these methods. When we need to develop a function, we need to use a combination function (there is a link between multiple functions, that is, there is one or more common global variables) and this combination function needs to be called in many places. If you simply set this combination function to a global function whose common variables are set to global variables, you will find a problem: I reference this combination function in a function, the global variable of the function after the reference has been obtained a data a, when we in the B function and trigger the combination function, Globally the global variable is modified to B, so that when we lose the data A. The use of closures can be a good solution to this problem, examples are as follows:
The code implements two kinds of "stand-alone" counter function Createcounter () {var counter = 0;return function () {Counter ++;console.log ("Number of events: "+ counter);}} var counter1 = Createcounter (), var counter2 = Createcounter (); Counter1 ();//number of Events:1counter1 ();//number of even Ts:2counter2 ();//number of Events:1counter1 ();//number of Events:3
Data independence for "JavaScript" closure applications