Anonymous functions and self-execution in Javascript

summary:Function is the most flexible object in JavaScript, here is just to explain the purpose of its anonymous function. Anonymous function: a function without a function name

Function is the most flexible object in JavaScript, here is just to explain the purpose of its anonymous function. Anonymous function: It is a function without a

function There are several types
of functions. The definition of a function can be roughly divided into three ways:

the first one: This is also the most conventional one.

function double(x){   
    return 2 * x;      
}
Second Type: This method uses the Function constructor, which takes both the parameter list and the function body as strings, which is very inconvenient. It is not recommended to use

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

var double = function(x) { return 2* x; }
Note that the function on the right of "=" is an anonymous function. After the function is created, the function is assigned to the variable double

. The creation of the anonymous function The
first way : This is the definition of the double function mentioned above, which is also one of the most commonly used ways.

The second way:

(function(x, y){  
    alert(x + y);    
})(2, 3);
here creates a Anonymous function (within the first parenthesis), the second parenthesis is used to call the anonymous function, passing in the parameters. Parentheses are expressions, and expressions have return values, so you can add a pair of parentheses after them to execute them

var a = 1; 
var b = 2; 
(function(){ 
    var b = 3; 
    a += b; 
})(); 
alert(a); // 4 
alert(b); // 2 
self-executing anonymous Function
Self- executing anonymous functions are functions of the form:
(function {// code})();
why (function {// code})(); can be executed, and function {// code}() ; will report an error?
First of all, it is necessary to be clear about the difference between the two: (function {// code}) is an expression, and function {// code} is a function declaration

. In the "compile" phase, the function declaration will be interpreted, but the expressions will be ignored.

When js is executed to function() {//code}();, since function() {//code} has been As explained, js will skip function{//code} and try to execute ();, so it will report an error; when js executes to (function {// code})();, because (function {// code} ) is an expression, and js will solve it to get the return value. Since the return value is a function, when (); is encountered, it will be executed. In addition, the method of converting a function into an expression does not necessarily depend on the grouping operator (), we can also use the void operator, the ~ operator, the ! operator...

function foo() { foo(); } // this is a self-executing function that executes itself internally, recursively

var foo = function () { arguments.callee(); }; // this is a self-executing anonymous Functions, since they don't have a named name, must use the arguments.callee property to execute themselves

var foo = function () { foo(); }; // This may also be a self-executing anonymous function, just the foo named name refers to itself. If you change foo to something else, you get a used-to-self-execute anonymous function

(function () { /* code */ } ()); // some people call this a self-executing anonymous function ( even if it isn't), because it doesn't call itself, it just executes immediately

(function foo() { /* code */ } ()); // Add a marked name to the function expression to facilitate debugging. But it must be named, the function is no longer anonymous

(function () { arguments. callee(); } ());
(function foo() { foo(); } ()); // Immediately called Function expressions (IIFE) can also be self-executing, but they may not be commonly used.
Anonymous functions and closures
The English word for closure is closure, which is a very important part of knowledge in JavaScript, because the use of closures can greatly reduce the amount of our code , to make our code look clearer, etc., in short, the function is very

powerful . The meaning of closure: closure is the nesting of functions. The inner function can use all the variables of the outer function, even if the outer function has been executed. Done (this involves the JavaScript scope chain)

function checkClosure(){ 
    var str = 'rain-man'; 
    setTimeout( 
        function(){ alert(str); } //This is an anonymous function 
    , 2000); 

checkClosure();
This example looks simple, careful analysis There are still many knowledge points in its execution process: the execution of the checkClosure function is instantaneous (maybe only 0.00001 milliseconds), a variable str is created in the function body of checkClosure, and str is not released after checkClosure is executed. It's because the anonymous function inside setTimeout has this reference to str. After 2 seconds, the anonymous function in the function body is executed, and str is released

. Use the closure to optimize the code:

function forTimeout(x, y){ 
    alert(x + y); 

function delay(x , y , time) { 
    setTimeout('forTimeout(' + x + ',' + y + ')' , time);     

/**
The above delay function is very difficult to read and difficult to write, but using closures can make the code more clear 
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 can also build namespaces to reduce global variables Use

var oEvent = {}; 
(function(){  
    var addEvent = function(){ /*code's implementation omitted */ }; 
    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 the web page. We want to use this code
http://click.aliyun.com/m/23508/

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326643558&siteId=291194637