Details of JavaScript anonymous functions and closure _javascript techniques

Source: Internet
Author: User
Tags closure

1. anonymous function
A function is one of the most flexible objects in JavaScript, and it simply explains the purpose of its anonymous function. anonymous function: A function that has no function name.

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

The first: This is also the most conventional one

Copy Code code as follows:

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

The second: This method uses the function constructor, the argument list and function body as a string, very inconvenient, not recommended.

Copy Code code as follows:

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

The third type:

var double = function (x) {return 2* x;}
Notice that the function to the right of "=" is an anonymous function that creates the function and assigns it to the variable square.

1.2 Creation of anonymous functions

The first way: this is the definition of the square function, which is one of the most common ways.

The second way:

Copy Code code as follows:

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

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

2. Closure Package
The closure of the English word is closure, this is a very important part of JavaScript knowledge, because the use of closures can greatly reduce the amount of our code, so that our code looks more clear and so on, in short, the function is very powerful.

What closures mean: closures are simply nested functions, and inner functions 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

Copy Code code as follows:

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

This example looks very simple, A careful analysis of its implementation has many points of knowledge: the execution of the Checkclosure function is instantaneous (perhaps just 0.00001 milliseconds), a variable str is created in the Checkclosure function body, and STR is not released after Checkclosure execution, which is There is a reference to this str for the anonymous function within settimeout. After 2 seconds, the anonymous function in the function body is executed, and STR is released.

Example two, optimizing code

Copy Code code as follows:

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 your code clearer
* Function delay (x, Y, time) {
* SetTimeout (
* Function () {
* Fortimeout (x, y)
*         }
*, time);
* }
*/

3. Examples
The biggest use of anonymous functions is to create closures, which are one of the features of the JavaScript language, and to build namespaces to reduce the use of global variables.

Example three:

Copy Code code as follows:

var oevent = {};
(function () {
The implementation of the var addevent = function () {//* code omits the */};
function Removeevent () {}

Oevent.addevent = addevent;
Oevent.removeevent = removeevent;
})();

In this code, functions addevent and removeevent are local variables, but we can use it through 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:

Copy Code code as follows:

var Rainman = (function (x, y) {
return x + y;
}) (2, 3);
/**
* can also be written in the following form, because the first parenthesis is only to help us 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 and initialize it to 5 by calling the anonymous function directly, which is sometimes very useful.

Example five:

Copy Code code as follows:

var outer = null;
(function () {
var one = 1;
function inner () {
One + + 1;
alert (one);
}
outer = inner;
})();
Outer (); 2
Outer (); 3
Outer (); 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 created the inner function, the inner function can access the variable one, and the global variable outer references inner, so the three call outer pops up the incremental result.

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

Example SIX:

Copy Code code as follows:

/**
* <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 you move the mouse over each <li&rt; element, it always pops up 4 instead of the element we expect. What is this for? Attention has been said (the final value). Obviously this explanation is too simple, when the MouseOver event invokes the listener function, first in the anonymous function (function () {alert (i);} The internal lookup defines I, the result is undefined, so it looks up, the result is already defined, and the value of I is 4 (the I value after the loop), so every time that it pops up is 4.

Workaround One:

Copy Code code as follows:

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

Workaround Two:

Copy Code code as follows:

var lists = document.getelementsbytagname (' li ');
for (var i = 0, len = lists.length i < len; i++) {
lists[I].$ $index = i; Record subscript by binding $ $index attribute on a DOM element
lists[I].onmouseover = function () {
Alert (this.$ $index);
};
}

Workaround Three:

Copy Code code as follows:

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);
}

4.2 Memory leaks

The use of closures is very easy to cause the browser memory leaks, in serious cases will be the browser hanging dead, interested in words can refer to: http://www.jb51.net/article/57404.htm

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.