The closure of anonymous functions and functions in JavaScript

Source: Internet
Author: User
Tags closure

1. anonymous function

A function is the most flexible object in JavaScript, and this is just about the purpose of its anonymous function. anonymous function: is a function that has no function name.

1.1 The definition of the function, the first simple introduction to the definition of function, roughly divided into three ways

The first: This is also the most conventional one

function double (x) {    return 2 * x;   }

Second: This method uses the function constructor, the parameter list and function body as strings, very inconvenient, not recommended.

var double = new Function (' x ', ' return 2 * x; ');

The third type:

var double = function (x) {return x;}

Note that the function on the right side of the "=" is an anonymous function that, after creating the function, assigns the function to the variable square.

1.2 Creation of anonymous functions

The first way: the definition of the square function, as described above, is one of the most common ways.

The second way:

(function (x, y) {    alert (x + y);  }) (2, 3);

An anonymous function (within the first parenthesis) is created, and the second parenthesis is used to invoke the anonymous function and pass in the parameter.

2. Closed Package

The English word for closures is closure, which is a very important part of JavaScript, because the use of closures can greatly reduce our code volume, make our code look clearer, and so on, in short, very powerful.

Closure meaning: The closure is the function of the nesting, the inner layer of the function can use all the variables of the outer function, even if the outer function has been executed (this involves the JavaScript scope chain).

Example One
function Checkclosure () {    var str = ' Rain-man ';    SetTimeout (function        () {alert (str);}//This is an anonymous function    , 2000);} Checkclosure ();

This example looks very simple, Careful analysis of its execution process is still a lot of knowledge points: The execution of the Checkclosure function is instantaneous (perhaps only 0.00001 milliseconds), in the Checkclosure function body created a variable str, after the completion of checkclosure execution, STR is not released, this is because This reference to STR exists for anonymous functions within settimeout. After 2 seconds, the anonymous function inside the function is executed, and STR is released.

Example two, optimizing the code
function Fortimeout (x, y) {    alert (x + y);} function delay (x, y  , time) {    setTimeout (' fortimeout (' +  x + ', ' +  y + ') ', time);    } /** * The delay function above is very difficult to read and not easy to write, but if you use closures you can make the code clearer * function delay (x, Y, time) {*     setTimeout (*         function () {*             Fortimeout (x, y)  *         }           *     , time);    * } */

3. Example

The biggest use of anonymous functions is to create closures (which is one of the features of the JavaScript language), and you can also build namespaces to reduce the use of global variables.

Example three:
var oevent = {};(function () {     var addevent = function () {/* code implementation omitted */};    function Removeevent () {}    oevent.addevent = addevent;    Oevent.removeevent = removeevent;}) ();

In this code, the functions addevent and removeevent are local variables, but we can use it through the global variable oevent, which greatly reduces the use of global variables and enhances the security of Web pages. We want to use this code: Oevent.addevent (document.getElementById (' box '), ' click ', Function () {});

Example four:
var Rainman = (function (x, y) {    return x + y;}) (2, 3);/** * can also be written in the following form, because the first parenthesis only helps us to read, but it is not recommended to use the following writing format. * var Rainman = function (x, y) {*    return x + y; *} (2, 3); */

Here we create a variable Rainman, which is sometimes very useful by directly invoking an anonymous function to initialize to 5.

Example five:
var outer = null; (function () {    var one = 1;    function inner () {one        + = 1;        alert (one);    }    outer = inner;}) (); outer ();    2outer ();    3outer ();    4

The variable one in this code is a local variable (because it is defined within a function), so the external is inaccessible. But here we create the inner function, the inner function has access to the variable one, and the global variable outer refers to inner, so three calls to outer will pop up the incremented result.

4. Note 4.1 Closures allow the inner layer function to refer to a variable in the parent function, but the variable is the final value

Example SIX:

/** * <body> * <ul> *     <li>one</li> *     <li>two</li> *     <li>three </li> *     <li>one</li> * </ul> */var lists = document.getelementsbytagname (' li '); for (var i = 0 , Len = lists.length; i < Len; i++) {    lists[i].onmouseover = function () {        alert (i);        };}

You will find that when the mouse moves over each <li&rt; element, it always pops up 4 instead of the element subscript we expect. What is this for? The notice has been said (final value). Obviously this explanation is too simple, when the MouseOver event invokes the listener function, first in the anonymous function (function () {alert (i);} If the internal lookup defines I, the result is undefined; so it looks up, the results are already defined, and the value of I is 4 (the I value after the loop), so the final pop-up is 4.

Workaround One:

var lists = document.getelementsbytagname (' li '); for (var i = 0, len = lists.length; i < Len; i++) {    (function (Inde x) {        lists[index].onmouseover = function () {            alert (index);            };                        }) (i);}

Workaround Two:

var lists = document.getelementsbytagname (' li '); for (var i = 0, len = lists.length; i < Len; i++) {    lists[i].$ $inde x = i;    Record subscript    lists[i].onmouseover = function () {        alert (this.$ $index) by binding the $ $index property on the DOM element;        }

Workaround Three:

function EventListener (list, index) {    list.onmouseover = function () {        alert (index);    };} var lists = document.getelementsbytagname (' li '); for (var i = 0, len = lists.length; i < Len; i++) {    EventListener ( lists[i], i);}

The closure of anonymous functions and functions in JavaScript

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.