Closure Usage Scenarios:
1. function as the return value, the following scenario
1 functionF1 () {2 varA = 100//Free Variables3 //returns a function (function as return value)4 return function(){5Console.log (a)//A is defined at the time of the scope, not the scope of the execution time, for the6 }7 }8 //F1 get a function9 varF1 =F1 ()Ten varA = 200//global scope, without affecting scope within a function OneF1 ()
2. function as a parameter pass
1 functionF1 () {2 varA = 100//Free Variables3 return function(){4Console.log (a)//free variable, parent scope search5 }6 }7 varF1 =F1 ()8 functionF2 (FN) {9 varA =300Ten fn () One } AF2 (F1)//Output
3. Application of closures in real development:
Closure applications are mainly used for encapsulating variables, convergent permissions
1 functionisfirstload () {2 var_list = []//inside the function, encapsulate the variable so that it cannot be modified externally3 return function(ID) {4 if(_list.indexof (ID) >= 0) {//The indexOf () method returns the position of the first occurrence of a specified string value in a string. If the string value that you want to retrieve does not appear, the method returns-1. 5 return false6}Else{7 _list.push (ID)8 return true9 }Ten } One } A - //Use - varFirstload =isfirstload () theFirstload (10)//true -Firstload (10)//false -Firstload (20)//true
Example: Create 10 a tags and click which number pops up
Error wording:
1 //wrong wording2 varI,a3 for(i = 0; i<10; i++){4A = document.createelement (' A ')5a.innerhtml=i+ ' <br/> '6A.addeventlistener (' click ',function(e) {7E.preventdefault ()//The preventdefault () method blocks the default behavior of an element (for example, when a Submit button is clicked to block the submission of the form). 8Alert (i)//I are all 10,i is a free variable, to go to the parent scope (global scope) to get the value, at which I was executed, the value is ten9 })Ten Document.body.appendChild (a) One }
Correct wording:
1 varI214 for(i = 0; i<10; i++){315 (function(i) {416varA = document.createelement (' A ')5a.innerhtml=i+ ' <br/> '6A.addeventlistener (' click ',function(e) {7E.preventdefault ()//The preventdefault () method blocks the default behavior of an element (for example, when a Submit button is clicked to block the submission of the form). 820alert (i)921st })Ten22Document.body.appendChild (a) One) (i)//Create a self-executing function A24}
The full solution of the knowledge point of JS face question (a closed packet)