My understanding: JavaScript functions work in the scope that it defines, not the scopes it executes, and the variables defined within the scope that it defines are global variables relative to this function,
This is the so-called "closure."
Look at an example: (Can you think of what the output is?) )
The <script>
function setupsomeglobals () {
var num = 666;
Galertnumber = function () {
alert (num);
};
Gincreasenumber = function () {
alert (num++);
}
Gsetnumber = function (x) {
num = x;
}
}
var num = 1;
Setupsomeglobals ();
Galertnumber (); 666
Gincreasenumber ();//666
galertnumber ();//667
Gsetnumber (a)
; Galertnumber ()//12
</script>
Here are 3 functions declared within the function setupsomeglobals () function: Galertnumber (), Gincreasenumber (), Gsetnumber (x), and a variable num declared inside the function setupsomeglobals () function. So, 3 internal functions Galertnumber (), Gincreasenumber (), Gsetnumber (x) should work in their "definition" Scope--function setupsomeglobals () Internally, and, correspondingly, the NUM variable is a global variable for these 3 internal functions in the setupsomeglobals () scope.
In this way, it is not difficult to understand the above output.
But, wait ... There are no problems found.
Num, as a local variable, is not destroyed after the closure is formed, which results in a memory leak. So be careful to use closures oh.
Reference: http://coolshell.cn/articles/6731.html