Anonymous functions and function closures in Javascript

Source: Internet
Author: User
ArticleDirectory
    • 1. Anonymous Functions
    • 2. Closure
    • 3. Example
    • 4. Note
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.

 
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.

 
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:

 
(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 ourCodeTo 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
 
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
 
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 and easy to write, however, if closure is used, the code can be clearer. * 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:
 
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:
 
VaR Rainman = (function (x, y) {return X + Y;}) (2, 3);/*** can also be written in the following format, because the first bracket only helps us read, but we do not recommend using 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 directly calling an anonymous function. This is sometimes very useful.

Example 5:
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 that the 4.1 closure allows the inner function to reference the variables in the parent function, but this variable is the final value.

Example 6:

 
/***** <Body> * <ul> * <li> one </LI> * <li> two </LI> * <li> three </LI> * <LI> one </LI> * </ul> */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 the mouse moves over each <Li & RT; element, 4 is always displayed, rather than the expected element subscript. Why? Note: (final value ). Obviously, this interpretation is too simple. When the Mouseover event calls the listening function, first check whether I is defined in the anonymous function () {alert (I, the result is not defined. Therefore, it will look up, the search result is defined, and the I value is 4 (The I value after the loop); therefore, in the end, 4 is displayed each time.

Solution 1:

 
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:

 
VaR lists = document. getelementsbytagname ('lil'); For (VAR I = 0, Len = lists. length; I <Len; I ++) {lists [I]. $ Index = I; // record the subscript lists [I] by binding $ index to the DOM element. onmouseover = function () {alert (this. $ index );};}

Solution 3:

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 closures can easily cause browser memory leakage. In severe cases, the browser may be suspended. For more information, see http://www.cnblogs.com/rainman/archive/2009/03/07/1405624.html.

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.