javascript--Closure Understanding

Source: Internet
Author: User
Tags closure variable scope

Last night listen to others talk about the closure of this thing, although the JS have a little understanding but not the slightest impression, today there is nothing to study the way to meet the curious baby. Integrated on-line understanding, record.

The scope of a closed package

To understand closures, you must first understand the special variable scope of JavaScript.

    • Global scope
    • Local scope: A function forms a separate scope, and the method scope can also be nested.

Unlike other languages: curly braces ({}) cannot form a separate scope, such as a scope in Java.

Let's say, for example, scope

1 varm = 1;2 functionf () {3     //here, a method scope is formed to protect the variables from being accessed externally .4      //method Scope provides access to global scopes5      varn = 2;6Alert (m);//will eject the M-value7     //Nested method Scopes8     functionF1 () {9         //There's a way to form a method scope again.Ten         //where you can access the external method scope One         varN1 = 3; A alert (n); -      } -      //You can't access F1 's variables out of the F1 scope. the      //alert (n1); Error -}
Second, closed package

After figuring out the scope of the problem, we can start chatting about closures.

Let's take the classic for loop as an example. You can try the following code, taken from the closure of the JavaScript Secret Garden loop

 for (var i = 0; i < i++) {    setTimeout(function() {        console.log (i);     );}

The output result is 10 10;

If you don't guess the right answer before you run it, that's right ...

    • First of all, why is the final output 10 times 10 instead of what you imagined 0, 1, 2, 3, 4, 5, 6, 7, 8,9

Because the settimeout is asynchronous!

You can imagine that because settimeout is asynchronous, we split this for loop into 2 parts.

The first part deals with the change of I value, and the second part is dedicated to settimeout

So we can get the following code:

    • // The first part of   i++;   ...    I/ /A total of 10 times   / / second part   setTimeout (function() {      Console.log (i);    );   ...   SetTimeout (function() {      console.log (i);    // 10 times in total.

      After such a demolition, I'm sure you know the results of the previous for-loop operation.

Since the variable i in the loop has been changing and eventually becomes 10, and the loop often executes settimeout, the method is not actually running, and when the real time is executed, the value of I has become 10!  

   I change the whole process is instantaneous, in short, faster than you asynchronous, even if you settimout is 0 milliseconds, will be done before you do.

    •  for (var i = 0; i < i++) {       setTimeout(function() {           console.log (i);        0);   }
    • So why is anonymous function in settimeout not forming a closure?

Because the anonymous function in settimeout does not pass I as a parameter to fix the value of the variable, it retains it, but instead directly refers to I in the outer scope, so I changes, which also affects the anonymous function.

So if we define an external function, let I pass in as a parameter "closure" we want the variable!!

    for(vari = 0; I < 10; i++) {       //Note that the key is that we pass the worth parameter of the desired closure into a method       //This method return a new method-closures !SetTimeout (FN (i), 1000); }   functionfn () {//for a deep understanding of closures, this function I did not use parameters       //The Magic "closure" happens in this step, in fact, the scope and value of replication plays a key role,       //for numbers/characters such as type is copy value, not reference       varA = Arguments[0]; return function() {console.log (a);//notice now that the variable I'm working on has become a,                                     //already and I do not have a half wool relationship!                                     //and the value of a is a definite value given at the time of execution,                                     //will not change because I change!       }; }
    • And a cleaner way to see if you can really understand closures.
    for (var i = 0; i < i++) {       (the value offunction(a)           {//  variable i is passed to this scope is copied to a,           //  So this value does not change with the external variable           setTimeout (function() {               Console.log (a);            );        // here we pass in parameters to "closure" variable   }

This is the closure, the simple point is specifically used to "package" variable.

Summarize:

(1) Closure is a design principle, it simplifies the user's call by analyzing the context, so that the user does not know the situation, to achieve his purpose;

(2) Online mainstream of the closure of the analysis of the article is in fact, and the closure of the principle of the reverse, if you need to know the closure of the details can be used well, the closure is a design failure;

(3) Learn as little as possible.

javascript--Closure Understanding

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.