// Example 1 var A = 10086; function F1 () {alert (a) ;}f1 (); // 999 // Example 2: when the internal variable of the function is declared, you must use var. Otherwise, a global variable function F2 () {var B = 10086;} F2 (); alert (B); // errer: B is defined // Example 3: for example, C is the global variable function F3 () {c = 10086;} F3 (); alert (C ); //// ======================================/// Example 2 we need to access B's what should I do when the value is set? // all the variables in F4 are visible to getd, however, the variables in getd are invisible to F4. in this way, our F4. // Example 4 function F4 () {var d = 10000; function getd () {alert (d);} return getd () ;}// closure definition: it can be simply understood as the purpose of the function defined inside the function // closure: Read the internal variables of the function and keep the value of the variable in the memory // Example 5 function F5 () {var n = 100086; add = function () {n + = 1}; function getn () {alert (n) ;}return getn ;} // In this case, no closure will occur when calling F5 (); // output 10086 add (); F5 (); // 10086 // use the fun variable, form the closure var fun = F5 (); // use fun to point to getn fun (); add (); fun (); // when var fun = F5 () is executed, variable fun actually points to the function getn, and getn uses the Variable N // when the function getn inside function F5 is referenced by function a's external variable, A closure // closure is created: After a is executed, it returns the result. The closure is not recycled because the Variable N is referenced externally, so n always exists, if we do not return getn, the value of N will not be called and will be recycled.
References
Uncover the true face of JavaScript closures
Learning JavaScript closures (closure)