One of the most important features in Javascript is the use of closures. Because of the use of closures, the current scope can always access external scopes. Because Javascript does not have block-level scope, only function scope, the use of closures is closely related to functions.
Mock private variables
Here Counter returns two closures: functions increment and get. These two functions maintain access to the Counter scope, so they can always access the variable count defined in the Counter scope.
How private variables work
Since Javascript cannot assign values and refer to scopes, in the above example, there is no way to directly access the internal private variable count from the outside. The only way to access it is by defining a closure.
The above code will not change the value of the count variable in the Counter scope because the hack is not defined within the Counter. The above code will only create or overwrite the global variable count.
Closure within a loop
One of the most common mistakes is using closures inside loops.
The above code will not output 0 to 9, but will output 10 times continuously.
The above anonymity will always maintain a reference to the variable i. When the console.log function is called to start output, the loop has ended and the variable i is already 10.
In order to avoid the above error, we need to create a copy of the variable i value each time through the loop.
Avoid citation errors
In order to copy the value of the variable in the loop, the best way is to add an anonymous immediate execution function in the outer layer.
This outer anonymous function receives the loop variable i as the first parameter and copies its value to its own parameter e.
The external anonymous function passes the parameter e to setTimeout, so setTimeout has a reference to the parameter e. And the value of this parameter e will not change due to external loop changes.
There is another way to achieve the same effect, which is to return an anonymous function in the anonymous function within setTimeout:
In addition, this can also be achieved through the bind method.
At the end of the article, let’s summarize:
(1) Closure is a design principle that simplifies the user’s calls by analyzing the context, allowing the user to achieve his or her purpose without knowing it;
(2) The mainstream articles on closure analysis on the Internet are actually contrary to the closure principle. If you need to know the details of the closure to use it well, the closure is a design failure;
(3) Study as little as possible.