Closures (closure)
Closures are a difficult point in JavaScript language and require sufficient logical thinking.
The scope of a variable
There are two types of variables: global variables and local variables.
1. Inside the function, you can read the global variable directly, as follows:
var n = ten; function fn () { alert (n);} FN (); Alert results are ten.
2. It is certainly not possible to read local variables inside the function outside of the function, as follows
function f () { var n =;}
f (); alert (n); program will error: n is no defined.
Note: It is important to note that in this place, you must add var when declaring a variable inside a function. If not added, it is equivalent to declaring a global variable.
second, how to read the local variables externally.
We introduce this closure here, to implement, is to introduce a function within a function.
function F1 () { var n = ten; function F2 () { alert (n); } return F2;} var result = F1 (); result (); The result is:10
third, what is called closures
Closure: A variable that is capable of reading other function intrinsics.
In fact, it can be simply understood as: a function defined within a function, such as the function F2 () in the example above.
Closures are essentially bridges that connect functions inside and outside of functions.
Iv. use of closures
1. You can read the variables inside the function.
2. Variable persistence (the value of the variable is always kept in memory).
function F1 () { var n = ten; return function () { n+ +; alert (n); }} var result = F1 (); // The external function assigns the variable result; Result (); // The result function executes for the first time and results in one; // The result function executes for the second time, and results in 12, which implements the summation,
The above example perfectly illustrates the persistence of variables.
3. Modular code to reduce the pollution of global variables.
var abc = (function() { ///ABC is the return value of the external anonymous function var a = 1; return function () { a+ +; alert (a); }}) (); ABC (); // 2; Call an ABC function, which is actually the return value of the internal function inside the call ABC (); // 3
Five, the use of closures should pay attention to the problems
1. The memory consumption is high because the closure causes the variables inside the function to be saved. Therefore cannot abuse the closure, otherwise may cause the webpage the performance question.
six, finally told everyone: in fact, the closure is a JavaScript language is a difficult point, but also its characteristics, a lot of advanced applications will be used to closure, so just learn the classmate do not understand also don't worry, in the future of continuous learning, will slowly understand!
JavaScript closures (closure)