Official explanation
A closure is an environment expression (usually a function) that has many variables and is bound to these variables. Therefore, these variables are part of the Environment expression.
General Explanation
All functions in Javascript are closures. But in general, nested functions produce more powerful closures, which are also what we call "closures" in most cases ". See the following code:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
<! --
// Outer function
Function (){
// Temporary variable I
Var I = 0;
// Inner function B
Function B (){
// Reference the outer temporary variable I
Alert (++ I );
}
// Execution result, returns the inner function B
Return B;
}
// Execute the outer function a and give c a reference pointing to the inner function B.
// If it is understood as normal, after this statement is executed, I will be recycled by GC. At this time, I should be "undefine"
Var c = ();
// Execute the inner function. Due to the closure, I in function B still references the external temporary variable I.
C ();
-->
</Script>
After var c = a () is executed, variable c actually points to function B, variable I is used in B, and then c () is executed () then a window will pop up showing the I value. This code is actually a closure. Why? Because variable c outside function a references function B inside function.
Garbage collection mechanism of Javascript
The closure is generated only because of the special garbage collection mechanism of javascript. The general rules for the Javascript garbage collection mechanism are as follows:
In javascript, if an object is no longer referenced, the object will be recycled by GC. If two objects are referenced by each other and are no longer referenced by 3rd, these two objects will be recycled. In the preceding script, function a is referenced by function B and function B is referenced by Function c outside function a. This is why function a is not recycled after execution.
Application scenarios of closures
1. Protect the security of variables in the function. In the preceding example, variable I in function a can only be accessed by function B, but cannot be accessed through other channels, thus protecting the security of I.
2. Maintain a variable in the memory. Still in the above example, because of the closure, I in function a is always in the memory, so every time c () is executed, I will add 1.
3. Implement JS private attributes and private methods (not externally accessible) by protecting the security of variables ). As follows, private attributes and private methods cannot be accessed outside the Constructor:
Copy codeThe Code is as follows:
Function Constructor (...) {
Var that = this;
Var membername = value;
Function membername (...) {...}
}