[See javascript]-Anonymous functions and closures from jquery (Anonymous function and Closure)

Source: Internet
Author: User

jquery Fragment:

[JavaScript]View Plaincopyprint?
    1. (function () {
    2. This ignores all implementations of jquery
    3. })();
(function () {//Ignore all implementations of jquery here}) ();

When I first contacted jquery six months ago, I was as excited as anyone to see what the source code was like. However, at the first sight of the source code, I was confused. Why is there only one anonymous function that doesn't see the run (of course it's running ...). ), can we have a library of jquery? So I came to csdn with a question. The result is that many people now know very well (because after me there is no shortage, hehe ~). When an anonymous function is enclosed, and then a parenthesis is appended to it, the anonymous function can run immediately! It's amazing!

Hey! Nonsense ends here. 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 on the forums-is this code a closed bag? With this 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 just forms, as long as it is beneficial to our application to achieve, is desirable--black cat white cat, caught mouse is a good cat! )

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

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

Of course, this is just a mathematical definition. However, in a computer programming language, the definition of a function is also sorta. Because, as we all know, the function in the computer is similar to the description in the mathematical definition, it is a set of code combination blocks that will return a unique output of some data that has been processed by a code-set logical operation. --Of course, the exception is that the input data is empty or the output data is empty, or both are empty.

Let's take a look at the concepts related to anonymous functions first.

    • Functions declaration (Function Statement)

To use a function, we must first declare its existence. The most common way to do this is to use a function statement to define one of the functions, such as:

[JavaScript]View Plaincopyprint?
    1. Function abc () {
    2. Code to process
    3. }
Function ABC () {//code to process}

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

[JavaScript]View Plaincopyprint?
    1. Function abc (x, y) {
    2. return x+y;
    3. }
Function abc (x, y) {return x+y;}

However, no matter how you define your functions, 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:

[JavaScript]View Plaincopyprint?
    1. Alert (typeof ABC);//"function"
Alert (typeof ABC);//"function"

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

    • Function Object

A function object is an intrinsic object within JavaScript, and all functions are actually a functional object. With regard to this discussion, let's leave it to the next thematic section. Let's see if the function object can directly use the constructor to create a new one. The answer is yes. For example:

[JavaScript]View Plaincopyprint?
    1. var abc = new Function ("X", "Y", "return x*y;");
    2. Alert (ABC (2,3)); "6"
var abc = new Function ("X", "Y", "return x*y;"); Alert (ABC (2,3)); "6"

I'm sure you should know something about how to declare a function. So what is an anonymous function?

    • Declaring anonymous functions

As the name implies, an anonymous function is a function without a real name. For example, we remove the name of the function from the example above, and then judge if he is a function:

[C-sharp]View Plaincopyprint?
    1. Alert (typeof function () {});//"function"
    2. Alert (typeof function (x, y) {return x+y;}); /"Function"
    3. 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"

It is easy to see that they are all function objects, in other words, they are functions, but they all have a feature--No name. So we call them "anonymous functions". However, because they do not have a "name", we have no way to find them. This extends the question of how to invoke an anonymous function.

    • Invocation of anonymous functions

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

[JavaScript]View Plaincopyprint?
    1. var abc=function (x, y) {
    2. return x+y;
    3. }
    4. Alert (ABC (2,3)); "5"
var abc=function (x, y) {return x+y;} Alert (ABC (2,3)); "5"

The above operation is tantamount to a different way to define the function, this usage is more frequently encountered by us. For example, when we set a DOM element event handler, we usually don't give them a name, but instead give it a corresponding event to reference an anonymous function.

The invocation of an anonymous function is actually another way of looking at the jquery fragment-using () enclosing the anonymous function, followed by a pair of parentheses (including the parameter list). Let's look at the following example:

[C-sharp]View Plaincopyprint?
    1. Alert ((function (x, y) {return x+y;}) (2,3)); /"5"
    2. 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. Think the application of strange people look at me the following paragraph of the explanation.

Do you know the effect of parentheses? Parentheses can combine our expressions and each block, that is, each pair of parentheses, has a return value. This return value is actually the return value of the 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 of one of the anonymous functions. Therefore, the parenthesis pair plus the anonymous function is like the name of the function that we get its reference position. So if you add a parameter list after the reference variable, the invocation form of the normal function is implemented.

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

[JavaScript]View Plaincopyprint?
    1. var abc=function (x, y) {return x+y;};/ /Assign anonymous function object to ABC
    2. The constructor of ABC is just like the constructor of anonymous functions. In other words, the implementation of the two functions is the same.
    3. Alert ((ABC). constructor== (function (x, y) {return x+y;}). constructor);
var abc=function (x, y) {return x+y;};/ /Assigning 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 the 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. This is the function body represented by the function object.

In summary, it is understood as the function object returned by the parenthesis expression, which is the anonymous function enclosed by parentheses, and can then be called as a normal argument list for this function object. (Here is a mistake, only the function expression can not directly call the function, the removal of the anonymous function parentheses must accompany the expression to assign value.) That is, (function () {alert (1)}) should be equivalent to A=function () {alert (1)} () and not even a=. )

    • Closed Package

What is a closure? Closures are code blocks in a programming language that allow a first-level function to exist and the free variables defined in the first-level function to be freed, until the first-level function is released, and the non-free free variables are applied outside the primary function.

How? Look at a sweat ... Yes, me too (though I do know, just a question of ability to express). Let's move on to a simpler way: closures, in fact, are a language feature, which refers to programming languages that allow functions to be treated as objects, and then be able to define instance (local) variables in functions like actions in an object, and those variables can be saved in the function to the instance object of the function until 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 still do not understand, then we simplify: closures, in fact, refers to the program language can let code call the function defined in the run of the local variables.

Now let's look at an example:

[JavaScript]View Plaincopyprint?
    1. var abc=function (y) {
    2. var x=y;//this is a local variable
    3. return function () {
    4. Alert (x + +);//This is where the first-level function in the closure attribute is called, and it is manipulated
    5. alert (y--);//argument variable referenced is also a free variable
    6. }} (5);//initialization
    7. ABC ();//"5" "5"
    8. ABC ();//"6" "4"
    9. ABC ();//"7" "3"
    10. alert (x);//Error! "X" is undefined!
var abc=function (y) {var x=y;//this is a local variable return function () {alert (x + +);//It is called the X of the first-level function local variable in the closure attribute, and it operates alert (y--);// The argument variable referenced is also a free variable} (5);//Initialize ABC ();//"5" "5" ABC ()//"6" "4" ABC ()//"7" "3" alert (x);//Error! "X" is undefined!

See here, can you judge whether the code snippet of jquery is closed?

As far as I understand it. If the closure feature is applied, you must determine if the code has the most important feature: a local variable that is not destroyed. It is clear, then, that the closure feature cannot be applied to anonymous functions without any implementation. But what if there are implementations in the anonymous function? It also has to be determined if there are any local variables that are not destroyed in its implementation. So if you ask the jquery code snippet in the opening, what features are used in JS? Then it's just an anonymous function and an anonymous function call. However, it implies closure characteristics and can be implemented at any time. Because JS is born with this feature! (This is just my understanding, I also want to know your understanding, welcome to communicate!) About closures, there is a chance to open a separate topic! )

Here to the previous understanding of the error, in the answer to CSDN you the question of the wrong answer to apologize--sorry ...

Because this note is a daytime jquery extension of JS knowledge point collation, so May and true JS learning does not take Xu, suggest beginners JS people or first look at the basic books it. However, the next few chapters should be on the basis of the collation of JS, the reading of the students can be difficult to first look at the following chapters. Thank you for your support!

[See javascript]-Anonymous functions and closures from jquery (Anonymous function and Closure)

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.