Anonymous functions of JavaScript and self-executing

Source: Internet
Author: User

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.

The definition of a function can be broadly divided into three ways:

The first: This is also the most conventional one

1 function Double (x) {    2     return 2 * x;        3 }

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

1 var Double New Function (' x ', ' return 2 * x; ');

The third type:

1 var Double function 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 double.

Creation of anonymous functions

The first way: the definition of the double function, which is described above, is one of the most commonly used methods.

The second way:

1 (function(x, y) {   2     alert (x + y);      3 }) (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. Parentheses are expressions, and expressions have return values, so you can add a pair of parentheses to them to execute them later.

Self-Executing anonymous function

1. What is a self-executing anonymous function?
It refers to a function such as this: (function {//code});


2. Questions
Why (function {//code}), can be executed, and function {//code} ();


3. Analysis
(1). First, be clear about the difference between the two:
(function {//code}) is an expression, and function {//code} is a functional declaration.
(2). Second, JS "pre-compilation" features:
JS in the "Pre-compilation" phase, will explain the function declaration, but will be suddenly token type.
(3). When JS executes to function () {//code} (), JS skips function () {//code} and attempts to execute () because function () {//code} has been interpreted in the "precompiled" stage;


When JS executes to (function {//code}) (), because (function {//code}) is an expression, JS will go to solve it to get the return value, because the return value is a function, therefore encountered (), it will be executed.

In addition, the method of converting a function to an expression does not necessarily depend on the grouping operator (), we can also use the void operator,~ operator,! Operator......

Such as: 

1 ! function () {   2   alert ("Alternative anonymous function self-executing");    3 } ();

anonymous functions and closures

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).

1 function checkclosure () {  2     var str = ' Rain-man ';   3     setTimeout (  4function         // This is an anonymous function   5     , +);   6 }  7 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.

To optimize the code with closures:

1 functionfortimeout (x, y) {2Alert (x +y); 3 }  4 functiondelay (x, Y, time) {5SetTimeout (' fortimeout (' + x + ', ' + y + ') ', time); 6 }  7 /**  8 * The delay function above is very difficult to read and not easy to write, but if you use closures you can make the code clearer9 * Function delay (x, Y, time) {Ten * SetTimeout ( One * Function () { A * Fortimeout (x, y) -  *         }             - *, time);  the  * }   -  */

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.

1 varOevent = {}; 2(function(){   3     varAddevent =function(){/*the implementation of the code omits the*/ }; 4     functionremoveevent () {}5      6Oevent.addevent =addevent; 7Oevent.removeevent =removeevent; 8})();

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

 1  var  Rainman = (function   (x, y) { 2  return  x + Y;   3 }) (2, 3 4  /*   5   * can also be written in the following form, because the first parenthesis just helps us to read,  However, it is not recommended to use the following writing format.  6   * var Rainman = function (x, y) { Span style= "color: #008080;"  >7   * return x + y;  8   *} (2, 3);  

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

1 varOuter =NULL; 2      3(function(){  4     varone = 1; 5     functioninner () {6One + = 1; 7 alert (one); 8     }  9Outer =inner; Ten })();  One       AOuter ();//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 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.

Attention

1 closures allow the inner layer function to refer to a variable in the parent function, but the variable is the final value

1 /**  2 * <body>3 * <ul>4 * <li>one</li>5 * <li>two</li>6 * <li>three</li>7 * <li>one</li>8 * </ul>9  */Ten       One varLists = document.getElementsByTagName (' li ');  A  for(vari = 0, len = lists.length; i < Len; i++){   -lists[I].onmouseover =function(){   - alert (i);  the     };  -}

You will find that when the mouse moves over each <li> 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:

1 varLists = document.getElementsByTagName (' li '); 2  for(vari = 0, len = lists.length; i < Len; i++){  3(function(index) {4lists[Index].onmouseover =function(){  5 alert (index); 6         }; 7 }) (i); 8}

Workaround Two:

 1  var  lists =  document.getElementsByTagName (' li '  2  for  ( var  i = 0, len = lists.length; i < Len;    I++ 3  lists[i].$ $index = i; //  by binding the $ $index property on the DOM element 4  lists[i].onmouseover = function   () { 5  alert (this  .$ $index);   6  };  7 } 

Workaround Three:

1 functionEventListener (list, index) {2List.onmouseover =function(){  3 alert (index); 4     }; 5 }  6 varLists = document.getElementsByTagName (' li '); 7  for(vari = 0, len = lists.length; i < Len; i++){  8 EventListener (lists[i], i); 9 }Ten2 Memory leaks

2 Memory leaks

The use of closures can easily cause browser memory leaks, in severe cases the browser hangs dead

Via http://www.jcodecraeer.com/a/jquery_js_ajaxjishu/2012/0628/290.html

Anonymous functions of JavaScript and self-executing

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.