On JavaScript anonymous function and closure

Source: Internet
Author: User
Tags closure function definition

one, anonymous function  //common function definition://individual anonymous function is unable to Run. Even if it is running, it cannot be called because there is no name. Such as: function () {            Alert (' 123 ');         }                       //syntax error, Unable to execute  1. simple use of:    var box =  function () {        return  ' Lee ';  & nbsp  }    Alert (box ());       //need to call the box () Method.  2. performing anonymous functions by self-execution     (function () {               //syntax format: (anonymous Function) ();    First parenthesis Place anonymous function, second parenthesis execution         alert (' 123 ')     }) ()  //assigns The return value of the anonymous function self-executing to the variable     var box =  (function () {        & nbsp       return 200;       }) ();    alert (box);              &NBSp  //reference above 1, call the box variable directly.  3. self-executing anonymous function parameters     (function (age) {        Alert (age);    }) () ;  4. function to put an anonymous function     function box () {         return function () {    &NB Sp        return ' pjh ';         }     }     alert ( Box () ());     //another method of invocation (more convenient):     var b = Box ();     alert (b ());   ii, closures     closures are functions that have access to variables in another function scope, and the usual way to create closures is to create another function within one function and access the local variables of the function through another Function.      The use of closures has one advantage, but also its disadvantage, that is, the local variables reside in memory, you can avoid the use of global variables. (global variable pollution leads to unpredictable application, and every module can be called for disaster!) therefore, It is recommended to use a private, encapsulated local variable).  
    1. Use anonymous functions to implement local variables that reside in memory and Accumulate.
function box () {var age = 100;               return function () {age++;            Return age;        }} var b = Box ();        Alert (b ());        Alert (b ());        Alert (b ());      b = null;        dereference, Waiting for garbage collection alert (b); The program will error, because B has been destroyed does not exist! PS: because the local variable returned by the scope in the closure is not destroyed immediately, it may consume more memory. Excessive use of closures can result in degraded performance, and it is recommended that closures be used if necessary.
    1. traversing the array by self-execution of the closure
        function Box () {            var arr = [];            for (var i=0;i<5;i++) {                 arr[i] = (function (num) {            &NB Sp        return function () {                  &N Bsp               return num;                and nbsp    }                 }) (i);        & nbsp;   }            return arr;         }        var b = Box ();        for (var i=0; I&L t;5; I++) {            alert (b[i] ());        } 
    1. about this object
    var box = {        getthis:function () {             return function () {                 return this;            }        }     };    alert (box.getthis ());       //return Object Window ps: normally, This is the Window in the global environment, if it is inside the object that points to the Object. closures, however, point to window at run time (because closures do not belong to properties or methods of this object).            example:    var user = "this window";      var box = {        user: ' This box ',        getthis: function () {            return function () {             return this.user;         &nBsp  }        }    };     Alert (box.getthis ());    //this window    alert (box.getthis (). call (box));   //this box ps:  Alert (box.getthis (). Call (box)); The role of call (box) is to impersonate an object.      improved:    var box = {        user: ' this box ',         getthis:function () {   //this is the scope of this is box            var that = this;            return function () {   //here scope This is window                return that.user;             }        }    };      Alert (box.getthis ());   //this window 
    1. memory leak problem
    ie the element that resides in memory cannot be destroyed in the browser, the browser needs to be closed before it is destroyed, so there is a memory leak, which needs to be cleaned up manually when you write your own code.      function Box () {        var Div = document.getElementById ("an ID for an HTML Page") & nbsp;       var text = div.innerhtml;        Div.onclick = function () {             alert (text);        };         DIV = null        //manual Contact Reference     } note:    JavaScript The declaration does not have a block-level scope such as:    function box () {        for (var index = 0; Index < 5; IND Ex++) {       /create Index object             var j = index;        }    alert (i);            //output the value of Index.     } ps: because JavaScript does not have block-level scopes, The local variables that are created are not automatically Destroyed.  

On JavaScript anonymous functions and closures

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.