Understanding of JavaScript Anonymous Functions (Thorough edition) _javascript tips

Source: Internet
Author: User
Tags anonymous closure
Copy Code code as follows:

(function () {
This ignores all implementations of jquery
})();
(function () {//This ignores jquery all implementations}) ();

When I first contacted jquery six months ago, I was as excited as anyone else to see what the source was like. However, at the first glimpse of the source, I was confused. Why is there only one anonymous function that does not see the run (of course it is running ...)? Can have jquery as a library of functions? So I came to csdn with doubt. The result believes that many people are very clear now (because after me also has the comer, hehe ~). When an anonymous function is enclosed and followed by a parenthesis, the anonymous function can be run immediately! It's amazing!

Hey! This is all nonsense. In this section, the jquery fragment we come across is a set of anonymous functions that run immediately. This usage has also provoked an overreaction in the forum-does this piece of code belong to a closure? With this in question, we start with the basics, analyze each key element, and look for answers that belong to you. (yes, my answer!) In my opinion, all theories are only forms, as long as it is beneficial to our application, is desirable-black cat, White cat, catch the mouse is a good cat! )

To say anonymous functions, we first need to start with the function itself. The function is defined as follows:

A function is a "rule" that assigns a unique output value to each input.

Of course, this is just a mathematical definition. However, in the computer programming language, the definition of function is also sorta. Because, as we all know, a function in a computer is similar to a description in a mathematical definition, it is a set of code combinations that will be entered into a number of data, processed by the logical operation of the code, and returned with a unique output. Of course, the exception is that the data entered is empty or the output data is empty, or both are empty.

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

Functions declaration (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:

Copy Code code 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.

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:

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. For the discussion of this aspect, let's leave it to the next feature section. 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:

Copy Code code as follows:

var abc = new Function ("X", "Y", "return x*y;");
Alert (ABC (2,3)); "6"
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:

Copy Code code 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:
Copy Code code as follows:

var abc=function (x,y) {
return x+y;
}
Alert (ABC (2,3)); "5"
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:

Copy Code code as follows:

Alert ((function (x,y) {return x+y;}) (2,3)); /"5"
Alert ((New Function ("X", "Y", "return x*y;") (2,3)); /"6"
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 ABC
The constructor of ABC is the same as the constructor of anonymous functions. In other words, the implementation of two functions is the same.
Alert ((ABC). constructor== (function (x,y) {return x+y;}). constructor);
var abc=function (x,y) {return x+y;};/ /Assign an anonymous function object to the ABC//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 linguistic feature, which refers to the programming language, which allows functions to be treated as objects, and can then be moved to define instance (local) variables in functions like operations in objects, 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 + +), or 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!
var abc=function (y) {var x=y;//this is a local variable return function () {alert (x + +);/That's where you call the X of the first-level function local variable in the closure attribute, and it operates alert (y--); The 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. Because JS is born with this feature! (This is just my understanding, I also want to know your understanding, Welcome to Exchange!) About closures, there is a chance or independent to open another topic! )
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.