In JavaScript, a function can be thought of as a kind of data that can be assigned to a variable and nested within another function.
var fun = function () {
console.log ("flat ramp");
}
function Fun () {
var n=10;
function Son () {
n++;
}
Son ();
Console.log (n);
}
Fun (); One
fun ();//11
Let's change the second paragraph of the code slightly:
var n=10;
function Fun () {
function son () {
n++;
}
Son ();
Console.log (n);
}
Fun (); One
fun ();//12
See the difference, if you can't understand the results of code execution, see a blog post about JavaScript scope and scope chain explanation.
In the above code, variable n is a global variable and may be assignable at any time without the need for a call to the fun function. To keep the variable n from being contaminated, or to reduce the pollution of global variables, we need to put N in a function as a local variable.
function Fun () {
var n=10;
function Son () {
n++;
Console.log (n);
}
Son ();
}
Fun (); One
fun ();//11
If we can call the son function directly in the global, then we can achieve the desired effect. The son function is now present as a local variable, and there are generally two ways to access it globally:
One is assigning to global variables
var A;
function Fun () {
var n=10;
A = function son () {
n++;
Console.log (n);
}
}
Fun (); Son ()
a ();//11
A ();//12
The other is to return a value using
function Fun () {
var n=10;
return function son () {
n++;
Console.log (n);
}
}
var a=fun ();
A ();
a ();//12
The son () function above is the closure, and in a sense all functions can be considered closures. Closures are functions that can access variables that are scoped to the outer function.
var A;
function Fun () {
var n=10;
A = function son () {
n++;
Console.log (n);
}
return a ();
}
Fun ();
a ();//12 a ();
//13
Fun ();//11 A (
);//12
A ();//13
Or the above code, we modify it slightly, and then look at the execution result, because the variable n is initialized every time the fun () function is executed.
The benefit of closures is to reduce global variables, avoid global pollution, and save local variables in memory. But this is both an advantage and a disadvantage, a piece of code if the closure is too much, it may cause memory leaks. Because local variables in closures are not reclaimed by the garbage collection mechanism, you need to manually assign null (about memory leaks, separate topics later)