On _javascript techniques of JavaScript anonymous function and self-execution function

Source: Internet
Author: User
Tags anonymous closure

A function is one of the most flexible objects in JavaScript, and it simply explains the purpose of its anonymous function. anonymous function: A function that has no function name.

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

The first: This is also the most conventional one

function double (x) {return 
2 * x; 
}

The second: This method uses the function constructor, the argument list and function body as a string, very inconvenient, not recommended.

var double = new Function (' x ', ' return 2 * x; ');

The third type:

var double = function (x) {return 2* x;}

Notice that the function to the right of "=" is an anonymous function that creates the function and assigns it to the variable square.

Creation of anonymous functions

The first way: this is the definition of the square function, which is one of the most common ways.

The second way:

(function (x, y) { 
alert (x + y); 
}) (2, 3);

An anonymous function (within the first parenthesis) is created here, and the second parenthesis is used to invoke the anonymous function and pass in the argument. Parentheses are expressions, and expressions have return values, so you can put a pair of parentheses behind them to perform.

Self-executed 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, function {//code} is a declaration of functions.
(2). Second, JS "precompiled" features:
JS in the "precompiled" phase, will interpret the function declaration, but will be a slight.
(3). When JS executes to function () {//code} (), because function () {//code} has been interpreted in the precompiled phase, JS skips function () {//code} to attempt to execute ();
When JS executes to (function {//code}), because (function {//code}) is an expression, JS will be able to solve it to get the return value, because the return value is a function, and 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, the ~ operator ...

Such as:

!function () { 
alert ("Alternative anonymous function self-execution"); 
} ();

Anonymous functions and closures

The closure of the English word is closure, this is a very important part of JavaScript knowledge, because the use of closures can greatly reduce the amount of our code, so that our code looks more clear and so on, in short, the function is very powerful.

What closures mean: closures are simply nested functions, and inner functions can use all the variables of the outer function, even if the outer function has been executed (this involves the JavaScript scope chain).

function Checkclosure () { 
var str = ' Rain-man '; 
SetTimeout ( 
function () {alert (str);}//This is an anonymous function 
, per); 
} 
Checkclosure ();

This example looks very simple, A careful analysis of its implementation has many points of knowledge: the execution of the Checkclosure function is instantaneous (perhaps just 0.00001 milliseconds), a variable str is created in the Checkclosure function body, and STR is not released after Checkclosure execution, which is There is a reference to this str for the anonymous function within settimeout. After 2 seconds, the anonymous function in the function body is executed, and STR is released.

Use closures to optimize your code:

function Fortimeout (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 the code clearer 
* Function delay (x, Y, time) { 
* settimeout ( 
* function () { 
* fortimeout (x, y) 
*} 
*, time); 
* } 
*/

The biggest use of anonymous functions is to create closures, which are one of the features of the JavaScript language, and to build namespaces to reduce the use of global variables.

var oevent = {}; 
the implementation of the function () {var addevent = function () {/* code omitted the */}; 
function Removeevent () {} 

oevent.addevent = addevent; 
Oevent.removeevent = removeevent; 
}) ();

In this code, functions addevent and removeevent are local variables, but we can use it through global variable oevent, which greatly reduces the use of global variables and enhances the security of Web pages.

We want to use this piece of code:

Oevent.addevent (document.getElementById (' box '), ' click ', Function () {});
var Rainman = (function (x, y) {return 
x + y; 
}) (2, 3); 
/** 
* can also be written in the following form, because the first parenthesis is only to help us read, but it is not recommended to use 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 calling the anonymous function directly, which is sometimes very useful.

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 created the inner function, the inner function can access the variable one, and the global variable outer references inner, so the three call outer pops up the incremental result.

Attention

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

/** 
* <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 you move the mouse over each <li> element, it always pops up 4 instead of the element we expect. What is this for? Attention has been said (the final value). Obviously this explanation is too simple, when the MouseOver event invokes the listener function, first in the anonymous function (function () {alert (i);} The internal lookup defines I, 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 every time that it pops up is 4.

Workaround One:

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:

var lists = document.getelementsbytagname (' li '); 
for (var i = 0, len = lists.length i < len i++) { 
lists[i].$ $index = i;//By binding the $ $index attribute to the DOM element record subscript 
lists[I ].onmouseover = function () { 
alert (this.$ $index);} 
; 
}

Workaround Three:

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 the browser memory leaks, in serious cases, the browser hangs dead

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.