Detailed description of closures in javascript, javascriptclosure
In javascript, a function can be considered as a type of data. It can be assigned to a variable and nested in another function.
Var fun = function () {console. log ("bottom slice ");}
function fun(){ var n=10; function son(){ n++; } son(); console.log(n);}fun(); //11fun(); //11
We can slightly modify the second code above:
var n=10;function fun(){ function son(){ n++; } son(); console.log(n);}fun(); //11fun(); //12
Can you see the difference? If you can't understand the code execution result, please read the previous blog article about the javascript scope and scope chain.
In the above Code, variable n is a global variable and may be assigned a value at any time without calling the fun function. To prevent Variable n from being contaminated, or to reduce global variable pollution, we need to put n in the function as a local variable.
function fun(){ var n=10; function son(){ n++; console.log(n); } son();}fun(); //11fun(); //11
If we can directly call the son function in the global environment, we can achieve the desired effect. The son function is now used as a local variable. To access the function globally, there are two methods:
One is to assign a value to a global variable.
var a;function fun(){ var n=10; a = function son(){ n++; console.log(n); }}fun(); //son()a(); //11a(); //12
The other is to use the return value.
function fun(){ var n=10; return function son(){ n++; console.log(n); }}var a=fun();a(); //11a(); //12
The above son () function is the closure. In a sense, all functions can be seen as the closure. A closure is a function that can access variables in the outer function scope.
var a;function fun(){ var n=10; a = function son(){ n++; console.log(n); } return a();}fun(); //11a(); //12a(); //13fun(); //11a(); //12a(); //13
In the above Code, let's modify it a little and check the execution result. This is because Variable n is initialized every time the fun () function is executed.
The benefit of the closure is to reduce global variables and avoid global pollution. You can save local variables in the memory. However, this is both an advantage and a disadvantage. If there are too many closures in a piece of code, memory leakage may occur. Because the local variables in the closure will not be recycled by the garbage collection mechanism, you need to manually assign null values (for Memory leakage, I will discuss it separately later)
Articles you may be interested in:
- JavaScript closure (closure)
- JavaScript anonymous functions and closures)
- Deep understanding of JavaScript series (16) Closures (Closures)
- Closure in JavaScript
- Detailed description of Javascript Closure (Closure)
- An example of javascript Closure usage