Preliminary study of the closure in JS

Source: Internet
Author: User

JS Advanced Programming (3rd) in the definition of closures is a sentence, the first closure is a function, what kind of function? A function that has permission to access a variable in another function scope.  The common way to create closures is to create another function inside a function, which is a nested function. The main point of closure is the ① scope chain (This principle allows us to understand that internal nested functions are able to access variables defined in the external parent function, whereas for nested functions referencing those variables defined in their own scope are often referred to as free variables) ② function execution mechanism (this involves the execution environment exe Cution Context, Environment stack (note that the bottom of the environment stack is always global context), active objects, variable objects, etc.). First of all, the execution environment is related: When the function executes, the environment of the function is pushed to the top of the environment stack, and when the function is executed, the environment pops up and the control is returned to the previous execution environment, but the situation will be different because of the closure. Another two related concepts: the active object (activation object) and the variable object (variable object) Variable object: Each execution environment will have its own variable object, which stores the variables and functions defined in the execution environment. If the execution environment is a function context, then its active object is used as the variable object, the active object also contains the arguments (the parameter class array), the formal parameters (the parameter's value), the active object also contains the argument Object, which has properties such as Callee,length, understands the above two points and can now describe the overall flow of function execution:
1, execute code, global execution Environment       Create global.  variable Object 2, assignment of global variable or call function       When a function is called, it gets the active object of the current function activation object , which contains the declaration of the function's internal variable, the declaration of the function, the parameter 3, the context of the function that was called       the assignment of variables at the scope of the function and various operations (scope includes global variable object and activation object for the current function execution Environment) 4, divided into three cases      a, function normal return or end, the function execution environment is ejected, go back to Step2 to continue executing other code;     b, if there is an intrinsic function in the function call, execute step 3;     c, if the function returns another function, and the function has a reference to the free variable, the closure is formed. At this time, the scope chain mechanism is still valid, the current execution environment function context will not be ejected environment stack, the function of the active object is also left in memory, will not be reclaimed by the garbage collection mechanism after the call ends. Go back to Step2 to continue executing other code; 5, all Code execution completed, program closed, free memory  
③ garbage collection mechanism in general, a function at the beginning of execution, the variables defined in the memory space to save, so that the subsequent statements are used, wait until the function is finished to return, these variables are considered useless, the corresponding memory space is also recycled. The next time the function is executed, all the variables return to their original state and are re-assigned to use. However, if a function parent is nested inside another function child, and this child function may be called externally, and this inner nested function child also uses the external function some variables in the parent, this time formed a closure, At this point, the memory recovery mechanism will be different from the previous general situation. When the external function parent executes the return and then calls the internal nested function directly, if the parent has been reclaimed by the general recycling situation, then the internal nested function cannot read the variables that have been recycled, so when the closure is encountered, The JS parser will actually save the inner nested function itself and the variables (free variables) of the parent and ancestor levels, and save them in the closure. And these variables are not recycled by the memory collector. This closure is destroyed only when these intrinsic functions are not possible to be called (such as being deleted or without pointers), and variables that are no longer referenced by the closure are recycled at the time the next memory recycle starts. Because the closure causes the variables in the function to be kept in memory all the time, the memory consumption is very high and the performance of the Web page is affected. So it is necessary for us to manually destroy the function after it has finished executing. Let's illustrate some of the characteristics of closures in the following example: There are two common forms of closures-functions as return values, and functions as parameter passes.
1 functionTest () {2     varnum = 1;3     return function() {4num++;5 console.log (num)6     }7 }8 varAnothertest =test ();9Anothertest ();//2TenAnothertest ();//3

As you can see, the variables that the closure makes reference to are always in memory (note that although the active object is not destroyed, the variable function that it contains still exists in memory, but it cannot be called directly) another example:
1 varresult = [];2 functionTest () {3     varnum = 0;4      for(; num < 3; num++) {5Result[num] =function() {6 console.log (num);7         }8     }9 }Ten test (); OneResult[0] ();//3 ARESULT[1] ();//3 -RESULT[2] ();//3
In the above code, the intent is to let the variable i in test be recycled using the internal anonymous function and output index 0 1 2, but the result is different from the expected. Why is it? Because the free variable recorded in the closure is only a reference to a free variable, it is said that only the value that the last state of the variable retains is obtained. The last value of the I variable after executing the FOR loop in this example is 3, so all references to the I value will be 3. There are two examples of the values of free variables:
1 varTest = 10;2 functionFun () {3     varTest = 100;4     return functionfoo (num) {5         if(Num <test) {6Console.log (num + ' < ' +test);7         }8     }9 }Ten varF1 =Fun (); OneF1 (15); A //15<100

As you can see in this example, the value of test is 100, and the 100来 is the parent function of the Foo function since the scope of the Foo function is created, so does the free variable come from the scope that created it or its parent scope? Look at an example:
1 varTest = 10;2parameter =function(num) {3     if(Num >test) {4Console.log (num+ ' > ' +test);5     }6 };7(function(fun) {8     varTest = 100;9Fun (15);Ten }) (parameter); One //15>10

In the above example, the value of test is 10, and this 10 is from the global scope. This proves that the free variable is actually taking the value in the scope of creating the function instead of its parent scope.

Preliminary study of the closure in JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.