JS Closure website: http://www.cnblogs.com/qieguo/p/5457040.html
What is JS closure
A function that has access to a variable within the scope of another function is a closure.
Here the F function accesses the variable n in constructor A, thus forming a closure. look at the code again .
1 function A () { 2 var n = 0; 3 function f () { 4 n++; 5 Console.log (n); 6 } 7 return F; 8 } 9 10 var C = A (); 11 c (); Console Output 1 12 C (); Console Output 2
See how it's done:
var c = couter (), this sentence couter () returns the function Inc, which is equivalent to var c = f;
C (), this sentence is equivalent to f (); Note that the function name is just an identifier (a pointer to a function) and () is the execution function.
The following three sentences are translated: var C = f; f (); f (); Is it different from the first code? No.
Why do you write like that?
We know that every function of JS is a small black house, it can get outside information, but the outside world can't directly see the content. Put the variable n into the small black room, in addition to the F function, there is no other way to contact the variable n, and in the function a outside the definition of the same name variable n is not affected, this is called enhanced "encapsulation."
The reason to return the function ID F with return is because the F function cannot be called directly outside the A function, so return f is associated with the outside.
The use of JS closures
http://blog.csdn.net/sunlylorn/article/details/6534610
Let's take a look at the use of closures. In fact, we can do a lot of things by using closures. such as simulating object-oriented code style, more elegant, more concise expression of code, in some ways to improve the efficiency of code execution.
1 anonymous self-executing functions
2 Cache
3 Implementing Encapsulation
Another important use of the 4 closures is to implement object-oriented objects, which provide a template mechanism for the class, and the traditional object language
JS Closed Package