Analysis of the method of creating and calling anonymous functions in JS

Source: Internet
Author: User
Tags anonymous closure constructor

An anonymous function is a function without a name, also called a closure function (closures), which allows temporary creation of a function without a specified name. Most often used as a value for a callback function (callback) parameter, many novice friends do not know about anonymous functions. Let's analyze it here.

function function name (argument list) {functional body;}

If you are creating an anonymous function, it should be:
function () {functional body;}

Because it is an anonymous function, there is generally no parameter passed to him.

Why do you want to create an anonymous function? Under what circumstances the anonymous function is used. There are two common scenarios for anonymous functions, one is callback function and the other is direct execution function.

Callback functions, such as AJAX asynchronous operations, require a callback function. Here is an unknown solution. As for the direct execution function, I can see one example:

The

code is as follows: <script language= "JavaScript" >


var a = "a";


(function () {


var a= "B";


alert (a);


})();


alert (a);


</script>


In the above code, two alert boxes are output sequentially. The first alert box has a content of B and the second is a. Have you seen any good? Yes, using a function to execute the scope of a variable directly, so that the same variables of different scripts can coexist.

Let's take a look at the concepts associated with anonymous functions first.

Function statement, to use a function, we have to declare its existence first. And our most common approach is to use function statements to define a function, such as:

The

code is as follows: function abc () {


//code to process


}


Function ABC () {//code to process}

Of course, your function can also be with parameters, even with the return value.

code is as follows: View Plaincopy to Clipboardprint?


function ABC (x,y) {


return x+y;


}


function ABC (x,y) {return x+y;}

However, no matter how you define your function, the JS interpreter translates it into a function object. For example, you define the function number of one of the above examples, and then enter the following code:

The

code is as follows: Alert (typeof ABC);//"function"

Your browser will pop up a prompt to prompt you that ABC is a function object. So what exactly is a function object?

Function Object

A function object is an intrinsic object in JavaScript, and all functions are actually objects of a function. Let's take a look at it, can the function object create a new function directly using the constructor? The answer is yes. For example:

The

code is as follows: var abc = new Function ("X", "Y", "return x*y;");


alert (ABC (2,3)); "6"


I believe you now have some idea of how to declare a function. So what is an anonymous function?

Declaring anonymous functions

Anonymous functions, as the name suggests, are functions that have no actual names. For example, we remove the name of the function in the example above and then judge if he is a function:

The

code is as follows: Alert (typeof function () {});//"function"


Alert (typeof function (x,y) {return x+y;}); /"function"


alert (typeof new Function ("X", "Y", "return x*y;")) "Function"


Alert (typeof function () {});//"function"


Alert (typeof function (x,y) {return x+y;}); /"function"


alert (typeof new Function ("X", "Y", "return x*y;")) "Function"

We can easily see that they are all function objects, in other words, they are functions, but they all have a feature--no names. So we call them "anonymous functions." However, because they have no "name", we have no way to find them. This expands the question of how to invoke an anonymous function.

Calls to anonymous functions

To call a function, we have to have a way to locate it and reference it. So, we'll need to find a name for it. For example:

The

code is as follows: Var abc=function (x,y) {


return x+y;


}


alert (ABC (2,3)); "5"

The above operation is tantamount to changing the way to define the function, this usage is more frequently encountered by us. For example, when we set up a DOM element event handler, we usually do not give them a name, but instead give it a corresponding event that references an anonymous function.

The call to an anonymous function actually has a practice where we see the jquery fragment--use () to enclose the anonymous function, followed by a pair of parentheses (containing the argument list). Let's take another look at the following example:

The

code is as follows: Alert ((function (x,y) {return x+y;}) (2,3)); /"5"


Alert ((New Function ("X", "Y", "return x*y;") (2,3)); /"6"

Many people may wonder why this method can be successfully invoked. I think the application of strange people just look at me for the following explanation.

Do you know the function of parentheses? Parentheses can divide our expression into chunks, and each piece, that is, each pair of parentheses, has a return value. This return value is actually the return value of an expression in parentheses. So, when we enclose the anonymous function with a pair of parentheses, the parentheses are actually returned, which is the function object for the anonymous functions. Therefore, the parentheses and the anonymous function are the names of the functions we have to get its reference position. So if you add the argument list after this reference variable, you implement the calling form of the normal function.

Do not know the above text to understand, if you can not understand, and then look at the following code to try it.

copy code code as follows: Var abc=function (x,y) {return x+y;};/ /Assign an anonymous function object to the ABC

The
//ABC constructor is the same as the constructor of the anonymous function. In other words, the implementation of two functions is the same.


alert ((ABC). constructor== (function (x,y) {return x+y;}). constructor);

Ps:constructor refers to the function that creates an object. Which is the function body represented by the function object.
In summary, it (the anonymous function contained in parentheses) is understood as a function object returned by the parentheses expression, and then the function object can be invoked as a normal argument list. (An error has been made here that only function expressions cannot call functions directly, and removing anonymous function parentheses must be accompanied by an expression assignment.) That is, (function () {alert (1)}) should be equivalent to A=function () {alert (1)} (), and cannot be removed even a=. )

Closed Bag

What's the closure? A closure is a code block in a program language that allows a class of functions to exist and the free variables defined in a first-level function are not released until the first-level function is released, and the free variables can be applied outside the first-level function.

How? Look at the sweat. It's OK, me too (though I know it, it's just a matter of expressing ability). Let's put it in a simpler way: closures, in fact, is a language feature, which refers to the programming language, which allows functions to be treated as objects, and can then define instance (local) variables in functions like operations in an object, and these variables can be stored in functions until the instance object of the function is destroyed. Other blocks of code can somehow get the values of these instance (local) variables and apply extensions.

I do not know if the explanation will be more clear, if you still do not understand, then we simplify: closures, in fact, refers to the program language can let code call the function of the operation defined in the local variables.

Now let's look at an example:

copy code code as follows: Var abc=function (y) {


var x=y;//this is a local variable


return function () {


Alert (x + +); This is where the x of the first-level function local variable in the closure attribute is invoked and manipulated


alert (y--);//referenced parameter variable is also a free variable


}} (5);//Initialize


ABC ()//"5" "5"


ABC ()//"6" "4"


ABC ()//"7" "3"


alert (x);//Error! "X" is not defined!


See here, can you tell if the jquery code fragment is closed?

As far as I understand it. Whether the closure attribute is applied, you must determine if the code has the most important element: a local variable that has not been destroyed. It is clear, then, that no anonymous function of any implementation can apply the closure attribute. But what if there is an implementation in the anonymous function? It also has to be sure that the local variables that were not destroyed were used in its implementation. So if you ask the jquery snippet in the opening paragraph, what is the feature in JS? So it's just a call to anonymous functions and anonymous functions. However, it implies closure characteristics, and can be implemented at any time by the closure of the package.

The most common usage:

The

code is as follows: (function () {


alert (' Water ');


})();


Of course, you can also take parameters:

The

code is as follows: (function (o) {


alert (o);


}) (' Water ');


A chained call to a function? Very simple:

copy code code as follows: (function (o) {


alert (o);


return Arguments.callee;


}) (' Water ') (' Down ');


Common anonymous functions are known to look at uncommon:

The

code is as follows: ~ (function () {


alert (' Water ');


}) ()//writing a bit cool ~


 


void function () {


alert (' Water ');


} ()//is said to be the most efficient ~


 


+function () {


alert (' Water ');


}();


 


-function () {


alert (' Water ');


}();


 


~function () {


alert (' Water ');


}();


 


!function () {


alert (' Water ');


}();


 


(function () {


alert (' Water ');


} ());//A bit of a compulsive taste ~

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.