The official explanation of closures is: an expression (usually a function) with many variables and an environment bound to these variables ), therefore, these variables are part of the expression. 1. What is a closure?
The official explanation of closures is: an expression (usually a function) that has many variables and an environment bound to these variables, so these variables are part of the expression.
Simply put, Javascript allows the use of internal functions-that is, function definitions and function expressions are located in the body of another function. In addition, these internal functions can access all the local variables, parameters, and other declared internal functions declared in their external functions. When one of these internal functions is called outside the external functions that contain them, a closure is formed.
Features of closures
1. nested Functions
2. The function can reference external parameters and variables.
3. Parameters and variables are not recycled by the garbage collection mechanism.
Generally, after the function is executed, the partial activity object is destroyed, and only the global scope is saved in the memory. But the closure is different!
Function fn () {var a =; function fn () {// you can access the value defined in fn alert (a ++) ;}fn ();} fn (); // function fn () {var a =; function fn () {// you can access alert (a ++);} return fn; //} var f = fn (); f (); // after execution, a is still in memory f (); // f = null; // a is recycled
The above is a small Editor to introduce you to the closure in JavaScript, I hope to help you!