The scope of a variable
To understand closures, you must first understand the special variable scope of JavaScript.
The scope of a variable is nothing more than two kinds: global variables and local variables.
The special point of the JavaScript language is that the global variables can be read directly inside the function.
Second, closure function example
JS Code
Function F1 () {
var n=999;
Nadd=function () {n+=1}
function F2 () {
alert (n);
}
return F2;
}
var result=f1 ();
Result (); 999
Nadd ();
Result (); 1000
In this code,result is actually the closure F2 function . It runs altogether two times, the first value is 999, the second value is 1000. This proves that the local variable n in the function F1 is kept in memory and is not automatically cleared after the F1 call.
F2 is assigned a global variable, which causes F2 to always be in memory, and F2 's presence depends on F1, so F1 is always in memory and will not be reclaimed by the garbage collection mechanism (garbage collection) after the call ends.
Another notable part of this code is the line "nadd=function () {n+=1}", which first did not use the var keyword in front of Nadd , so Nadd is a global variable, not a local variable. Second, the value of Nadd is an anonymous function (anonymous functions), and this
The anonymous function itself is also a closure, so nadd is equivalent to a setter that can manipulate local variables inside the function outside of the function.
JS Closed-Packet function