闭包 is a function that has access to a variable in another function scope, the most common way to create a closure is to create another function within one function and access the local variables of the function through another function
The disadvantage of closures is that resident memory increases memory usage and is prone to memory leaks if used improperly.
Closures are javascript a major feature of language, the main application of closures is mainly to: design private methods and variables.
After the general function is executed, the local active object is destroyed and only the global scope is saved in memory. But the case of closures is different!
A little more convenient is :
Closure is actually a bridge between the external function and the internal function, through the return of the function, the function of the outside of the object call function internal variables, methods and so on.
Before we know about closures, let's take a look at the function scope and pre-parsing process by two examples:
//1 functionfn () {varI=0; varfn1=function() {console.log (i); }; I++; varFn2=function() {console.log (i); }; return[FN1,FN2]; } varARR=FN ();//i is already equal to 1, this can only be determined I's scope is the I in FNArr[0] ();//1 This will only start calling Fn1, and when I call I already equals 1.ARR[1] ();//1 This will only start calling fn2, and when I call I already equals 1.
After reading must you also understand, then we come again the closure problem: (take the following closure function example)
//2 functionff () {varI=0; //return function () {} implementation closure return function(){ return++i; } } varF1=ff ();//0 //FF (), a closure environment is formed, so the data stored in the context is not destroyed because the reference to the I in return function () {} points to the I variable under FF //The call is executed once, but the value of I is not destroyed because the return function has a dependency on FF ()Console.log (F1 ());//1Console.log (F1 ());//2Console.log (F1 ());//3
Then summarize the following closures:
1. Local variables are not destroyed after the execution of the Geot, because the local variable is dependent on the external part.
The * * Function has determined the scope of the free variable at the time of declaration * *
2. Closure is to extend the scope of the variable;
JS Closed Package