JavaScript anonymous functions and closures-javascript tips-js tutorial

Source: Internet
Author: User
This article introduces anonymous functions and closures in detail, provides detailed examples and precautions. It is a very good article and is recommended to you. 1. Anonymous Functions
Functions are the most flexible objects in JavaScript. Here we will only explain the usage of anonymous functions. Anonymous function: A function without a function name.

1.1 define a function. First, let's briefly introduce the definition of a function, which can be roughly divided into three methods.

First: this is also the most common one.

The Code is as follows:


Function double (x ){
Return 2 * x;
}

Second: This method uses the Function constructor and uses the parameter list and Function bodies as strings. This method is inconvenient and is not recommended.

The Code is as follows:


Var double = new Function ('x', 'Return 2 * x ;');

Third:

Var double = function (x) {return 2 * x ;}
Note that the function on the right of "=" is an anonymous function. After the function is created, the function is assigned to the variable square.

1.2 create an anonymous Function

The first method is to define the square function, which is also one of the most common methods.

Method 2:

The Code is as follows:


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

An anonymous function (in the first bracket) is created here, and the second bracket is used to call the anonymous function and input parameters.

2. Closure
The English word closure of closures is a very important part of JavaScript knowledge, because using closures can greatly reduce the amount of our code and make our code look clearer, in short, the function is very powerful.

The meaning of the closure: To put it bluntly, it is the nesting of the function. The inner 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 1

The Code is as follows:


Function checkClosure (){
Var str = 'rain-Man ';
SetTimeout (
Function () {alert (str);} // This is an anonymous function.
, 2000 );
}
CheckClosure ();

This example looks very simple. After careful analysis, there are still many knowledge points in its execution process: the execution of the checkClosure function is instantaneous (it may only take 0.00001 milliseconds ), A variable str is created in the checkClosure function. After the checkClosure is executed, str is not released because the anonymous function in setTimeout has reference to str. After 2 seconds, str is released after the anonymous function in the function is executed.

Example 2: optimize the code

The Code is as follows:


Function forTimeout (x, y ){
Alert (x + y );
}
Function delay (x, y, time ){
SetTimeout ('fortimeout ('+ x +', '+ y +') ', time );
}
/**
* The preceding delay function is hard to read or write, but the code can be clearer if closure is used.
* Function delay (x, y, time ){
* SetTimeout (
* Function (){
* ForTimeout (x, y)
*}
*, Time );
*}
*/

3. Example
The biggest use of anonymous functions is to create closures (one of the features of the JavaScript language) and build namespaces to reduce the use of global variables.

Example 3:

The Code is as follows:


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 both local variables, but we can use 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 4:

The Code is as follows:


Var rainman = (function (x, y ){
Return x + y;
}) (2, 3 );
/**
* It can also be written in the following format, because the first bracket only helps us read, but the following writing format is not recommended.
* Var rainman = function (x, y ){
* Return x + y;
*} (2, 3 );
*/

Here we create a variable rainman and initialize it to 5 by directly calling an anonymous function. This is sometimes very useful.

Example 5:

The Code is 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 in a function), so it cannot be accessed externally. But here we have created the inner function. The inner function can access the variable one and reference the global variable outer to the inner. Therefore, the incremental result is displayed when outer is called three times.

4. Note
4.1 The closure allows the inner function to reference the variable in the parent function, but the variable is the final value.

Example 6:

The Code is as follows:


/**
*
*


    *
  • One

  • *
  • Two

  • *
  • Three

  • *
  • One

  • *

*/

Var lists = document. getElementsByTagName ('lil ');
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

Solution 1:

The Code is as follows:


Var lists = document. getElementsByTagName ('lil ');
For (var I = 0, len = lists. length; I <len; I ++ ){
(Function (index ){
Lists [index]. onmouseover = function (){
Alert (index );
};
}) (I );
}

Solution 2:

The Code is as follows:


Var lists = document. getElementsByTagName ('lil ');
For (var I = 0, len = lists. length; I <len; I ++ ){
Lists [I]. $ index = I; // record the subscript by binding the $ index attribute to the Dom Element
Lists [I]. onmouseover = function (){
Alert (this. $ index );
};
}

Solution 3:

The Code is as follows:


Function eventListener (list, index ){
List. onmouseover = function (){
Alert (index );
};
}
Var lists = document. getElementsByTagName ('lil ');
For (var I = 0, len = lists. length; I <len; I ++ ){
EventListener (lists [I], I );
}

4.2 Memory leakage

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

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.