Simple Application of JavaScript closure, javascript Closure
Closure Definition
In JavaScript, when an internal function is referenced by a variable other than its external function, a closure is formed. In short, closures are functions that can read internal variables of other functions.
Function of closure:
1. Read the internal variables of the function.
2. Keep the values of these variables in the memory.
Simple Application of closures
Example 1:
Function a () {var I = 0; function B () {console. log (++ I);} return B;} var c = a (); // After var c = a () is executed, variable c points to function B, after executing c (), the I value (1) is displayed ). C (); // output 1
Example 2:
(Function () {var I = 0; return function () {console. log (++ I) ;}}) (); // output 1
Example 3:
(Function (I) {return function () {console. log (++ I) ;}}) (0) (); // output 1
Example 4:
For (var I = 0; I <3; I ++) {setTimeout (function (I) {return function () {console. log (I) ;};}) (I), 2000); console. log (I + 10);} // output 10 11 12 (two seconds later) 0 1 2
Example 5:
For (var I = 0; I <3; I ++) {setTimeout (function (I) {return function () {console. log (I) ;};}) (I) (), 2000); console. log (I + 10);} // output 0 10 1 11 2 12 immediately (the program stops running in two seconds)
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.