- What is a closure package
A closure is a function that has access to a variable in another function's scope (a bit of a mouthful), and the simple point is to create another function inside a function and return a reference to the function. (This is also a common way to create closures)
function Outerfunc (outernum) { returnfunction innerfunc (innernum) { Outernum= outernum+innernum; return outernum;} } var inner=outerfunc (1); var a1=inner (one), Console.log (A1)// output isvar a2=inner (2 ); Console.log (A2)// output is
The above code creates a closure that Innerfunc has access to the variable outernum of the outside function.
Don't understand, it's okay, let's look at the memory of executing this function
In JavaScript, there is a concept called scope, and we define a function below
function sample (value1,value2) { var temp; Temp=value1+value1; return temp;} var result=sample (5,6);
When the sample function executes, the scope chain is as follows
Each execution environment in the background has an object (variable object) that represents the variable. The variable object for the global environment always exists, while a local environment variable object such as the sample () function exists only during the execution of the function.
When sample (5,6) executes, the scope chain of the execution environment of sample is destroyed, and the active object of sample () is not referenced, then the active object of sample () is destroyed, such as a dashed red box indicating that it will be destroyed. Because the global variable object requires the entire execution environment to be destroyed before it is destroyed (the entire program executes, after the program exits).
Now let's go back to the initial closure and see what the scope chain of this closure is.
For example, when Outerfunc (1) executes, the Outerfunc execution environment scope chain will be destroyed, that is, the red dashed box part of the expression is destroyed, the original Outerfunc () of the active object is to be destroyed, but the system detected, Outerfunc () The active object is also referenced by the Innerfunc execution environment scope chain, so it is preserved, meaning that the value inside is also preserved.
After the execution of inner (11), outernum=12, and then execute inner (2), outernum=14
Understanding JavaScript Closures