This article mainly introduces JavaScript closures to you in detail. Speaking of closures, I believe that students who write front-ends all know it, and I believe that closures have been used more or less in actual projects. So what exactly is a closure, and how does it come about?
1. What is a closure?
Mentioned in Teacher Ruan’s article:
A closure is a function that can read the internal variables of other functions. Since in the Javascript language, only sub-functions within the function can read local variables, closures can be simply understood as "functions defined inside a function".
2. The function of closure
One is to read the variables inside the function, and the other is to keep the values of these variables in the memory.
3. A simple closure example
function count() { let num = 0; return function add() { return ++num; } }let a = count(); a(); //1a(); //2
First, count() The return result is the function returned in the count() function and assigned to a. At this time, the local variable num defined in count() is saved in memory. When a() is called for the first time, ++num is returned, which is 1; when a() is called for the second time, since num is 1 at this time, the returned result is 2
4. The reason for closure
I believe many people are confused about this issue. They think that a function returns a function, thus forming a closure. In fact, this is just the method of closure, not the reason. The reason will be explained below. The main reason
is generated is because JavaScript is lexically scoped, that is, it has been given a scope when the function is defined . Then at runtime, it will be assigned a runtime scope based on the actual running situation. Only through these two scopes can a JS function be executed correctly.
Taking the above example as an example, when executing count(), the scope of the function is
Runtime scope num = 0 |
---|
Lexical scope |
When count() is executed and the add function is returned, because add is in ## at this time #Define the state, so the lexical scope of the function generated when returning is the scope of the above count(). So when a() is executed, its real scope is
5. SummaryFrom the above description, it can be seen that when generating a closure, the local variables (runtime scope) of the external function are used as lexical by the internal function The scope is stored in memory, so the memory will not be released until the internal function is released. Therefore, when using closures, you need to be very careful about memory leaks.