Function outerfunc (){
VaR privateattr = 10;
Return function (){
Privateattr * = 2;
Return privateattr;
};
}
// Call the outerfunc function to return a reference to the innerfunc function,
// This reference is assigned to the variable refinnerfunc.
VaR refinnerfunc = outerfunc ();
Alert (refinnerfunc ());
// Call the innerfunc function through the refinnerfunc reference.
Refinnerfunc (); // return 20 variable privateattr can be accessed and modified by innerfunc
Refinnerfunc (); // return 40
// Call the outerfunc function and create a copy of The innerfunc Function
VaR refinnerfunc2 = outerfunc ();
Refinnerfunc2 (); // return 20 the value of the privateattr variable in different copies is independent.
When a JavaScript function is returned, the JS parser retains all the variables and functions in its scope.
The word closure visually describes the fact that the function scope is stored in a closed package.
The variables and functions in the function scope can be released and recycled until the function is no longer referenced by other objects.
According to the explanation of the Java recycle mechanism, after the local variables in the method are executed,
If it is no longer referenced by other objects, the garbage collector can choose the appropriate time to recycle these local variables.
However, the garbage collection mechanism of JS is different from that of Java.CodeThe execution result.
The garbage collection mechanism of JS is also to recycle variables or methods that are no longer referenced by other objects,
However, because JS references can not only point to variables, but also to functions, in the above js code,
As long as the reference to the function innerfunc is not set to null,
The local variables in the innerfunc scope of the function will not be recycled by the JS garbage collector.
The local variable privateattr is considered to be in a secure and relatively closed "closure" environment,
The only way to access it is to call the innerfunc function in the same scope.
Until the innerfunc function is no longer referenced by other objects, the variables and functions in its scope can be released and recycled.