What is a closure package :
when an intrinsic function in the scope that defines it the external when referenced , the inner function's closure is created , and if the intrinsic function references a variable that is located outside the function, when the external function call is complete , the These variables are not freed in memory because the closures require them .
Example 1
function Outerfun ()
{
var a=0;
function Innerfun ()
{
a++;
alert (a);
}
return innerfun; Watch this .
}
var obj=outerfun ();
obj (); result is 1
obj (); result is 2
var obj2=outerfun ();
Obj2 (); result is 1
Obj2 (); result is 2
Example 2
function Foo () {
var i = 0;
return function () {
Console.log (i++);
}
}
var f1 = Foo (),
F2 = Foo ();
F1 ();
F1 ();
F2 ();
0 1 0
since the In the Javascript language, only sub-functions inside the function can read local variables, so the closure can be simply understood as " a function defined inside a function ".
The maximum use of closures is two, one is the ability to read variables inside the function, and the other is to keep these variables in memory, that is, the closure can make it the birth of the environment has always existed. Take a look at the following example, the closure allows internal variables to remember the result of the last call.
So memory consumption is very large. Therefore cannot abuse the closure, otherwise may cause the webpage the performance question.
JS in the closure (accumulation summary)