Anonymous functions of JavaScript and self-executing

Source: Internet
Author: User

The first: This is also the most conventional one

123 functiondouble(x){        return2 * x;       }

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

1 vardouble = newFunction(‘x‘, ‘return 2 * x;‘);

The third type:

1 vardouble = function(x) { return2* 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.

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:

123 (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. 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 (), and we can also use the void operator, the ~ operator, and the operator ...

Such as:

123 !function(){     alert("另类的匿名函数自执行");   }();

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

1234567 function checkclosure () {       Code class= "JS keyword" >var str = ' Rain-man ' Code class= "JS plain" >;       settimeout (            function () {alert (str);} //This is an anonymous function        , ";  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:

12345678910111213141516 function forTimeout(x, y){      alert(x + y);  function delay(x , y  , time){      setTimeout(‘forTimeout(‘ +  x + ‘,‘ +  y + ‘)‘ , time);      /**   * 上面的delay函数十分难以阅读,也不容易编写,但如果使用闭包就可以让代码更加清晰   * function delay(x , y , time){   *     setTimeout(   *         function(){   *             forTimeout(x , y)    *         }             *     , time);      * }   */

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.

12345678 var oEvent = {};  (function(){       var addEvent = function(){ /*代码的实现省略了*/ };      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 () {});

12345678 var rainman = (function(x , y){      return x + y;  })(2 , 3);  /**   * 也可以写成下面的形式,因为第一个括号只是帮助我们阅读,但是不推荐使用下面这种书写格式。   * 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.

1234567891011121314 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 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

12345678910111213141516 /**   * <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> 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:

12345678 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:

1234567 var lists = document.getElementsByTagName(‘li‘);  for(var i = 0, len = lists.length; i < len; i++){      lists[ i ].$$index = i;    //通过在Dom元素上绑定$$index属性记录下标      lists[ i ].onmouseover = function(){          alert(this.$$index);          };  }

Workaround Three:

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

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.