Example
var generateclosure = function () {
var count = 0;
var get = function () {
count++;
return count;
};
return get;
};
var counter = generateclosure ();
Console.log (counter ()); Output 1
Console.log (counter ()); Output 2
Console.log (counter ()); Output 3
In this code, there is a local variable count in the Generateclosure () function, with an initial value of 0. There is also a function called GET, where get adds 1 to the count variable in its parent scope, which is the generateclosure () function, and returns the value of count. The return value of Generateclosure () is the Get function. On the outside we call the Generateclosure () function through the counter variable and get its return value, which is the Get function, and then repeatedly call counter (), we find that each value is incremented by 1.
Let's take a look at what the above example does, and according to the usual imperative programming mindset, count is a variable within the generateclosure () function, whose life cycle is generateclosure () called, when Generateclosure () when returned from the call stack, the space requested by the count variable is also freed. The problem is that, at the end of the Generateclosure () call, counter () refers to the "already freed" count variable and, instead of making an error, modifies and returns count each time it calls counter (). What's going on here?
This is the characteristic of the so-called closures. When a function returns a function that is defined internally, a closure is generated, and the closure includes not only the returned function, but also the defined environment of the function. In the example above, when the inner function of the function generateclosure () is referenced by an external variable counter, the local variable of counter and Generateclosure () is a closure.
Example
var generateclosure = function{
var count = 0;
var get = function () {
count++;
return count;
};
return get;
};
var counter1 = Generateclosure ();
var counter2 = Generateclosure ();
Console.log (Counter1 ()); Output 1
Console.log (Counter2 ()); Output 1
Console.log (Counter1 ()); Output 2
Console.log (Counter1 ()); Output 3
Console.log (Counter2 ()); Output 2
"Web front end" javascript closures