"JS advanced 3" closures and anonymous functions

Source: Internet
Author: User

You want to learn about closures first look at what is an anonymous function!    (i) anonymous functions         anonymous functions are functions that do not have a name. He has two ways of declaring it:        1. Typical function Declarations:        Function functionname (arg0,arg1,arg2) {           / /function Body        }       2. function Expression:        var functionname = function (ARG0,ARG1,ARG2) {            //function Body        }   Although the two approaches are equivalent in logic, they still differ.    Difference 1: The former is loaded into the scope before code execution, while the latter is meaningful when the code executes to that line.    Difference 2: The former assigns a name to the function, while the latter creates an anonymous function and assigns the anonymous function to a variable.           in other words, the second example above: Creates an anonymous function with 3 parameters and assigns the anonymous function to the variable functionname, The anonymous function is not given a name.   (ii) Closures    The book defines this: a function that has access to a variable in another function's scope    but that's a myth that's hard for beginners to understand. In fact, in essence, closure is the function of the inside and outside the functionA bridge connected together.          1. So I'll start by saying why there is a concept of closure, what is the meaning of it?         (1) First we learned the previous scope, and we know a concept: The function can read the global variable directly inside.         so look at the code:       var n=999;     function f1 () {   alert (n);    }    f1 ();  //& nbsp;999        (2) then another concept: The local variables within the function cannot be read naturally in the outside of the function           then look at the code:        FUNCTION F1 () {   var  n=999;    }     alert (n);  //output Error          (3) Here's a place to be aware that when declaring variables inside a function, be sure to use the var command. If not, you're actually declaring a global variable! (We've talked about it before!) )        function f1 () {   n=999;    }      F1 ();     alert (n);  // 999        the key here! : That is, how to read the local variables from the outside?          that is, in the inside of the function, define a function. (i.e. closures!!) )         function f1 () {        var  n=999;      function f2 () {        alert (n ); // 999      }      }         in the above code, the function F2 is included inside the function F1, and all local variables inside the F1 are visible to the F2. But the opposite is not possible, F2 internal variables, the F1 is not visible. Since F2 can read the local variables in the F1, we can not read its internal variables outside the F1 as long as the F2 is the return value! See Code:        FUNCTION F1 () {         var n=999;      function f2 () {         Alert (n);      }              return f2;      }          VAR RESULT = F1 ();          result (); //999   This code differs from the above in that it takes the F2 function as a return value and then calls it. You must be thinking about what the last two lines mean. In fact, I did not make sense at the beginning, after the expert guidance, in fact, this last two lines means to call F2 the return value of this function. Are these two lines easier to understand if I rewrite them?        VAR RESULT = F1 ();        result ();        merger becomes: F1 () (); Actually the result is the same          can also better illustrate F2 this closure is done by using it as the return value (because it can access local variables within the function F1) and then invoking the return value from the global environment. This naturally achieves our purpose---Read the variables inside the local function from the global scope!        2. Now that you know the meaning of closures, let's look at the use of closures.         (1) The first use of closures, actually mentioned above, is to produce its meaning: you can read the variables inside the function          (2) The second use of closures is that the values of these variables can always be kept in memory         the second use how to understand it? See Code:        FUNCTION F1 () {     &NBsp;     var n=999;            nadd=function () {                n+=1           }            FUNCTION F2 () {    alert (n);    } & nbsp;         return f2;      }        var result=f1 ();    // The return value of the F1 function (which is the form of the function F2) is given to Result       result ();           // 999    output The return value of this F2         nadd ();             //Call nAdd function         result ();           // 1000   here is the second purpose of closure: F2 This closure causes the value of the variable N to always be kept in memory    Light by code to understand the second use, as if there is no convincing, the following use of the method of drawing to let everyone more profound understanding!!             The second use is actually linked to the scope chain, and I'll explain the next:  . When the closure F2 is returned from the F1 function, its scope chain is initialized to the active object containing the F1 function and the global variable object (the black line portion). This allows F2 to access all the variables defined in the F1 () function. More importantly, even if F1 () is executed, its active object will not be destroyed, because F2 this closure also refers to the F1 function of the active object, which is why the second purpose of the above reason: the closure will keep the variable in memory until the closure is destroyed.

JS advanced 3 closures and anonymous functions

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.