The scope of a variable
The special point of the JavaScript language is that the global variables can be read directly inside the function.
On the other hand, a local variable inside a function cannot be read naturally outside the function.
Function F1 () {
var n=999;
}
alert (n); Error
Second, how to read the local variables from the outside?
For a variety of reasons, we sometimes need to get local variables within the function. However, as already mentioned, under normal circumstances, this can not be done, only through the workaround to achieve.
That is, in the inside of the function, define a function. (In the above example, the value of the variable n cannot be accessed outside the function F1, if you want to access the value of the variable n outside the function F1, you need to define a function F2 within the function F1, then F2 is able to access the value of the variable n, and then return the function F2, in this way, Then the value of the variable n can be accessed outside the function F1, where the function F2 is a closure)
Function F1 () {
n=999;
function F2 () {
alert (n);
}
return F2;
}
var result=f1 ();
Result (); 999
JS Closed Package