Anonymous functions of JavaScript and self-executing

Source: Internet
Author: User

This article and everyone to share is mainly in JavaScript anonymous function and self-executing related content, come together to see it, hope to learn JavaScript help you. 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 without a function nameThe functions are divided into severalThe definition of a function can be broadly divided into three ways: the first: This is also the most conventional onefunctionDouble(x) {return2 * x;} Second: This method uses the function constructor, the argument list and function body as strings, very inconvenient, not recommended to usevarDouble =NewFunction(' x ', ' return 2 * x; '); The third type:varDouble =function(x) {returnx; 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 doublecreation of anonymous functionsThe first way: the definition of the double function, which is one of the most commonly used methods, is the second way: (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 after them to executevarA = 1;varb = 2; (function() {var b = 3;a + = b;}) (); alert (a); 4alert (b); 2self-Executing anonymous functionA self-executing anonymous function is a function that is shaped like this:(function{//code}) ();Why (function {//code}), can be executed, and function {//code} ();1. First, be clear about the difference between the two:(function {//code})is an expression,function {//code}is a function declaration. 2.3. Second, JS "precompiled" features: JS in the "pre-compilation" stage, will explain the function declaration, but will suddenly token. 4.5. When JS executes tofunction () {//code} ();When, becausefunction () {//code}In the "precompilation" phase has been explained, JS will skipFunction{//code}, trying to execute();, it will be error; When JS executes to(function {//code}) ();When, because(function {//code})Is the expression, JS will go to solve it to get the return value, because the return value is a function, therefore encountered();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...... 6.functionFoo() {foo ();} This is a self-executing function that executes itself within the function, recursivelyvarFoo =function() {Arguments.callee ();}; This is a self-executing anonymous function, because there is no label name, you must use the Arguments.callee property to perform your ownvarFoo =function() {foo ();}; This may also be a self-executing anonymous function, only the Foo flag name refers to itself. If you change Foo to something else, you will get a Used-to-self-execute anonymous function (function() {/* code */} ()); Some people call this a self-executing anonymous function (even if it's not), because it doesn't call itself, it just executes immediately (functionFoo() {/* code */} ()); Add an indication name to the function expression to facilitate Debug. But it must be named, and the function is no longer anonymous (function() {Arguments.callee ();} ());(functionFoo() {foo ();}   ()); Immediately called function expressions (Iife) can also be self-executing, but may not be commonly usedanonymous functions and closuresThe English word for closures is closure, which is a very important part of JavaScript, because using 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 function can use all the variables of the outer function, even if the outer function has been executed (this involves the JavaScript scope chain)functioncheckclosure(){varstr = ' Rain-man '; SetTimeout (function() {alert (str);}//This is an anonymous function, 2000);} Checkclosure (); This example looks 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), a variable is created in the function body of checkclosure STR is not released after Checkclosure execution, because the anonymous function in SetTimeout has this reference to Str. Until 2 seconds after the anonymous function inside the function is executed, STR is freed to optimize the code with closures:functionFortimeout(x, Y) {alert (x + y);}function Delay(x, Y, time) {setTimeout (' fortimeout (' + x + ', ' + y + ') ', time);} The delay function above/** is very difficult to read and not easy to write, but if you use closures you can make your code clearerfunctionDelay(x, Y, time) {SetTimeout (function() {fortimeout (x, y)}, time);} The biggest use of the anonymous function 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 variablesvarOevent = {};(function(){varAddevent =function() {/* code implementation omitted */};functionremoveevent() {}oevent.addevent = Addevent;oevent.removeevent = removeevent;}) (); In this code, the functions addevent and removeevent are local variables, but we can use them through the global variables oevent, which greatly reduces the use of global variables and enhances the security of Web pages. We want to use this snippet of code oevent.addevent (document.getElementById (' box '), ' click ',function() {}); var Rainman = (function(x, Y) {returnx + y;}) (2, 3);/* can also be written in the following form, because the first parenthesis only helps us to read, but it is not recommended to use the following writing format var Rainman =function(x, Y) {returnx + y;} (2, 3); * * Here we create a variable Rainman and initialize it to 5 by calling the anonymous function directly, which is sometimes very usefulvarOuter =NULL;(function(){varone = 1;functionInner() {One + = 1;alert (one);} outer = inner;})    (); outer ();    2outer ();    3outer (); 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 can access the variable one, and the global variable outer refers to inner, so three calls to outer will pop up the result of the incrementNote:1 closures allow the inner layer function to refer to a variable in the parent function, but the variable is the final value/*<ul><Li>oneli><Li>twoli><Li>threeli><Li>oneli> ul> */var lists = document.getelementsbytagname (' li '); for (var i = 0, len = lists.length; i < Len; i++) {lists[I].onmouseover = function () {alert (i);};} You'll notice that when you move the mouse over each element, it 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 finds whether I is defined inside the anonymous function (function () {alert (i);}), and the result is undefined; so it looks up, the result is already defined, and the value of I is 4 ( The I value after the loop); So, the final pop-up is 4.Workaround One:varLists = document.getElementsByTagName (' li '); for(vari = 0, len = lists.length; i < Len; i++) {(function(index) {lists[Index].onmouseover =function() {alert (index);};}) (i);}Workaround Two:varLists = document.getElementsByTagName (' li '); for(vari = 0, len = lists.length; i < Len;    i++) {lists[i].$ $index = i; Record subscript lists[I].onmouseover by binding the $ $index property on the Dom elementfunction() {alert (this.$ $index);};}Workaround Three:functionEventListener(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 using closures can easily cause browser memory leaks, in severe cases the browser hangs dead Source: Geek Headlines

Anonymous functions of JavaScript and self-executing

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.