Understanding of JavaScript closures

Source: Internet
Author: User
Tags variable scope

Read a lot about how to understand closures, but most of the article is to copy or explain the "JavaScript Advanced Programming (Third Edition)" for the closure of the explanation, even the routine is invariably quoted Elevation 3,181 page ' Closure and variable ' section of the "Return array of items, Results The values of each item are the same "routine, there are some articles explaining the process of the span between the previous step and the next is simply skyrocketing rise, let people repeatedly look at the half-day can not understand.

The understanding of closures requires a lot of concepts to pave the way, including variable scope chain, execution environment, variable activity object, reference garbage memory collection mechanism, if you do not understand the concepts involved in this article, you can go to this "advanced JavaScript Programming (third edition)" Take a good look and understand these concepts.

I am also writing some examples and carefully read and understand Gao Cheng and closure related concepts and knowledge, finally to the closure of a certain understanding, in order to test the effect of learning, especially write an article in order to test whether they really understand and master.

Before we understand closures, let's take a look at the small things that make it easier to ignore closures.

Example 1:
function foo () {    var a = 1;     return A;     // 1

The above example is very well understood, if a function return a value, then the function can be used as a return value directly, whether it is a reference type (function, array) or basic data type.

Example 2:
function foo () {    function  foos () {        var b = 2;         return b;            }     // uncaught Referenceerror:foos is not defined

This example shows that if a function B is declared inside a function A, then outside of function A, calling function B directly from function B's function name will cause undefined error. You can understand that a local scope rule in a variable scope rule also holds for a function declaration.

Example 3:
function foo () {        var a = 1;         function Foos () {        return A;   Note: The returned a is a variable defined in Foo, not a variable defined in Foos.      }        Console.log (Foos ());}; Foo (); // 1

Example 3 shows that Foos can only be executed within Foo, which conforms to our understanding of "local scope rules in variable scope rules, as well as function declarations."

///Example 4:
functionfoo () {vararr =NewArray ();
for(vari=0;i<10;i++) {Arr[i]=function(){ returni; }; } return function(){ for(varK = 0;k<arr.length;k++) {Console.log (Arr[k] ()); } };}; Console.log (foo () ());//output 10 x;

In Example 4, the Execution of Foo () is one of the anonymous functions returned by Foo (as shown below):

return function () {        for (var k = 0;k<arr.length;k++) {            console.log (Arr[k] ());        }        }; 

Well, at this point we need to do this again. Get the anonymous function, in order to get the last value (i.e.: 10 10), and execute the resulting anonymous function (we might call it function C), Foo has been executed once, this time foo's variable i value is already 10, because the variable object is assigned by reference, So this time the closure function in Foo (that is, the anonymous function that references the variable I of Foo ) again refers to the variable I of Foo, then the resulting value is naturally 10. The key here is the time of execution with the closure function within Foo, and if the closure function is executed immediately and then assigned to Arr[i], then we can get the desired value from 0 to 9;

///Example 5:
functionfoo () {vararr =NewArray (); for(vari=0;i<10;i++) {Arr[i]=function(){ returni; }(); } return function(){ for(varK = 0;k<arr.length;k++) {Console.log (arr[k]); } };}; Console.log (foo () ());//0 to 9

For a more detailed explanation of Example 4:
In Example 4, according to the JavaScript reference garbage collection mechanism (the rule of this mechanism is: there are more than 0 references to the variable should not be destroyed), although the function foo has been executed, but this variable I of Foo because the anonymous function (we may call it function B) reference, So this I was still not destroyed by the garbage collection program, so where does this I exist at this time? Certainly not exist in the execution environment of function Foo, because the rules for executing environment creation and destruction are: When a function is created, the execution environment of the function is created, and once the function is executed, the execution environment is destroyed immediately. Therefore, this I can only exist in the execution environment of the anonymous function (function B) inside Foo, which not only has its own scope and its own variable object, but also contains the scope of its outer function foo and the variable object of foo. The variable i exists in the scope of the Foo that function B contains and in the Variable object. Since JavaScript cannot directly manipulate memory space, JavaScript can only access variable objects in a reference way, and when the value of the variable I of Foo is already 10, then execute the closure function of foo (function B). Then the reference to I will naturally get 10.

Understanding of JavaScript closures

Related Article

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.