One: What is closures
JS advanced programming says that closures refer to functions that have access to variables in another function scope.
Second: The use of closures
A common way to create closures is for child functions to be nested inside the parent function, so that the child functions can access the variables in the parent function.
1 functionAdd () {2 varA=1;
Call the Inneradd function .3 return function(){4a++;5 Console.log (a);6 }7 }8 Add () ();9 Add () ();TenConsole.log ("------------------------"); One varAddafter=Add (); A Addafter (); -Addafter ();
8 Row----2
9 Row-----2
12,13 Line---2,3
So why is the result of line 9th still 2, not expecting 3?
This is because JS also has the garbage collection mechanism in C # java.
(1) The function is not referenced, and after execution, the function scope is reclaimed.
(2) If the function is referenced by another variable, the function scope is saved.
8th, Line 9, the Add () function is not referenced by other variables, but simply executes, so the scope of a is only present in the function.
11 Rows, the Add () function is referenced by an external variable addafter, and the value of a in the function is stored in memory.
It can be said that if the Inneradd function is referenced by a function other than the Father function add, then a closure is formed, otherwise it cannot be formed.
There is another form of use:
1 varAddmatch= (function(){2 varA=22;3 return function(){4a++;5 Console.log (a);6 }7 })();8 Addmatch ();9Addmatch ();
Three: The problem of closures
Closures can only take the last variable value in the containing function , saving the entire variable object, not a particular variable.
1 var arr1=[12,19,3],arr2=[],arrlength=arr1.length; 2 for (var i=0;i<arrlength;i++) {3 arr2[i]=function() {4 Console.log (i); 5 return i; 6 }; 7
Four: Application scenarios for closures
Js-I understand the closure