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

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

2 Memory leaks

The use of closures is very easy to cause browser memory leaks, in severe cases the browser hangs Dead.

The source of this article: 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.