What is a closure
A closure is a function that can access a variable in the scope of another function. As we know, function scopes are isolated and closed, and the external execution environment is not accessible, but closures are. Examples are as follows:
Function f1(){var n=999; } alert (n); // errorCopy the code
How do I get local variables from the outside? We simply define a function f2 inside the f1 function, f2 as the return value, and we can read its internal variables outside f1. As follows:
The function f1 () {var n = 999; The function f2 () {alert (n); } return f2; } var result = f1 (); result(); / / 999Copy the code
The f2 function of the above code is the closure.
The principle of closures
The implementation principle of closures, in fact, takes advantage of the properties of the scope chain. We know that the scope chain is that when you access a variable in the current execution environment, if it doesn’t exist, you go all the way to the outer layer, and finally find the outermost layer, which is the global scope, and thus form a chain.
The role of closures
1. You can read variables inside a function. 2. Keep variables in memory.
Why are variables kept in memory? , let’s look at the following code:
The function f1 () {var n = 999; NAdd bring them any closer = function () {n + = 1} function f2 () {alert (n); } return f2; } var result = f1 (); // result equals f2 result(); / / 999 nAdd bring them any closer (); result(); / / 1000Copy the code
The above code runs twice, the first with a value of 999 and the second with a value of 1000, which also shows that the local variable n in the function f1 is kept in memory and is not automatically cleared after the f1 call.
Disadvantages of closures
1. Closures can cause variables in functions to be stored in memory, which consumes a lot of memory. Therefore, do not abuse closures, otherwise it will cause web performance problems and may lead to memory leaks in IE. The solution is to remove all local variables that do not apply before the function exits. 2. Improper use of closures can cause variables not to be collected by the garbage collection mechanism, resulting in memory leaks.
Why aren’t variables collected and destroyed by the garbage collection mechanism when closures are used? This is because of the garbage collection mechanism: JS states that within a function scope, variables are destroyed when the program is finished executing, thus saving memory. When using closures, by the nature of the scope, variables outside the closure (function) are not destroyed because the function is always called and therefore always exists, so excessive use of closures can cause memory leaks.
Refer to the link: www.ruanyifeng.com/blog/2009/0… Segmentfault.com/a/119000002…