Understanding of JavaScript anonymous functions (thorough Version)

Source: Internet
Author: User

 

I can't understand many explanations on the Internet. I want to know the principle... This article should be thorough.

 

Query segment: View plaincopy to clipboardprint?

  1. (Function (){
  2. // All jquery implementations are ignored here
  3. })();

When I first came into contact with jquery six months ago, I was as excited as others to see what the source code looked like. However, at the first glance of the source code, I am confused. Why is there only one handler name function running? (of course it is running ......), Is there a function library like jquery? So I came to csdn with questions. As a result, I believe that many people are now very clear (because there are many new people after me, haha ~). When an anonymous function is enclosed and a bracket is added to it, the function can run immediately! Amazing!

Hey! So far. In this section, the jquery snippet we encounter is a set of anonymous functions that run immediately. This kind of usage has also aroused heated debate on the Forum-does this code belong to a closure? With this question, we start from the basics, analyze each key element, and find our own answers. (Yes, your answer! In my opinion, all theories are just forms. As long as they are conducive to our application implementation, it is desirable-black cat, white cat, and good cat !)

To say anonymous functions, we should first start with the functions themselves. 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 computer programming languages, the definition of functions is also far from 10. As we all know, functions in computers are similar to descriptions in mathematical definitions. They areAfter processing several pieces of input data with logic operations set by the Code, a unique set of code combination blocks are returned.-- Of course, the exception is that the input data is null, the output data is null, or both are empty.

Next, let's take a preliminary look at concepts related to anonymous functions.

  • Function declaration (function Statement)

To use a function, we must first declare its existence. The most common method is to use a function statement to define a function, such:

View plaincopy to clipboardprint

Function ABC (){

  1. // Code to process
  2. }

 

Of course, your function can also contain parameters or even return values.

  1. Function ABC (x, y ){
  2. Return X + Y;
  3. }

 

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

  1. Alert (typeof ABC); // "function"

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

  • Function object

Function objects are inherent objects in Javascript. All functions are actually function objects. We will leave this discussion to the next special topic section. Let's first look at whether the function object can directly use the constructor to create a new function? The answer is yes. For example:

  1. VaR abc = new function ("X", "Y", "Return x * Y ;");
  2. Alert (ABC (2, 3); // "6"

 

I believe you have some knowledge about how to declare a function. So what is an anonymous function?

  • Declare anonymous Functions

As the name implies, an anonymous function is a function without a real name. For example, we can remove the name of the function in the above example and determine whether it is a function:

  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"

 

We can easily see that they are all function objects. In other words, they are all functions, but they all have a feature-No Name. So we call them "anonymous functions ". However, we cannot find them because they do not have a "name. This raises the question of how to call an anonymous function.

  • Call of anonymous Functions

To call a function, we must have a method to locate it and reference it. Therefore, we need to find a name for it. For example:

  1. VaR abc = function (x, y ){
  2. Return X + Y;
  3. }
  4. Alert (ABC (2, 3); // "5"

 

The above operation is actually equivalent to defining a function in another way. This usage is frequently encountered. For example, when we set a DOM element event processing function, we usually do not set their names, but assign the corresponding event to reference an anonymous function.

There is also another way to call an anonymous function, that is, the jquery snippet we see -- use () to enclose an anonymous function, and then add a pair of parentheses (including the parameter list ). Let's take a look at the following example:

  1. Alert (function (x, y) {return X + Y;}) (2, 3); // "5"
  2. Alert (new function ("X", "Y", "Return x * Y;") (2, 3); // "6"

 

Many may wonder why this method can be called successfully? If this application is strange, let's take a look at the following explanation.

Do you know the role of parentheses? Parentheses can combine our expressions into blocks, and each block, that is, each pair of parentheses, has a return value. The returned value is actually the return value of the expression in parentheses. Therefore, when we enclose anonymous functions with a pair of parentheses, in fact, parentheses return the function object of an anonymous function. Therefore, adding an anonymous function to the parentheses is like a function with a name, and we get its reference position. Therefore, if the parameter list is added after the referenced variable, the call form of the common function is implemented.

I don't know if you can understand the above text. If you still can't understand it, let's try the following code again.

  1. VaR abc = function (x, y) {return x + y ;}; // assign an anonymous function object to ABC
  2. // The constructor of ABC is the same as the constructor of anonymous functions. That is to say, the implementation of the two functions is the same.
  3. Alert (ABC). constructor = (function (x, y) {return X + Y;}). constructor );

 

PS: constructor refers to the function for creating objects. That is, the function body represented by the function object.

In short, it is understood as the function object returned by the parentheses expression (the anonymous function included in the parentheses), and then the function object can be called as a normal parameter list. (The preceding error indicates that only function expressions cannot directly call functions. To remove Anonymous function brackets, assign values to the expressions. That is, (function () {alert (1)}) () should be equivalent to a = function () {alert (1, cannot even remove a = .)

  • Closure

What is a closure? A closure refers to a code block in a programming language that allows a level-1 function to exist and the free variables defined in the level-1 function cannot be released until the level-1 function is released, these unreleased free variables can also be applied to a level-1 function.

How? See a sweat ...... It's okay, so do I (although I understand it, it's just a matter of expression ability ). Let's change to a simpler method: closure is actually a language feature. It refers to a programming language that allows functions to be viewed as objects, then, you can define instance (local) variables in functions like operations in objects. These variables can be saved to the function until the Instance Object of the function is destroyed, other code blocks can get the value of these instance (local) variables in some way and perform application extension.

I don't know whether it will be clearer after this explanation. If I still don't understand it, Let's simplify it: closure, actually, it refers to the local variables defined in the function that can be called by the code in the program language.

Now let's look at an example:

  1. VaR abc = function (y ){
  2. VaR x = y; // This is a local variable.
  3. Return function (){
  4. Alert (x ++); // This is the X of the local variable of the first-level function in the closure feature.
  5. Alert (y --); // The referenced parameter variable 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 not defined!

VaR abc = function (y) {<br/> var x = y; // This is a local variable <br/> return function () {<br/> alert (x ++); // here, X of the local variable of the first-level function in the closure feature is called, and operate on it <br/> alert (y --); // The referenced parameter variable is also a free variable <br/>}} (5 ); // initialization <br/> ABC (); // "5" "5" <br/> ABC (); // "6" "4" <br/> ABC (); // "7" "3" <br/> alert (x); // error! "X" is not defined! <Br/>

Can you determine whether the code snippet of jquery is closed?

Let me understand it. Whether the closure feature is applied, you must determine whether the Code contains the most important elements: local variables not destroyed. Obviously, the closure feature cannot be applied without any implemented anonymous functions. But what if an anonymous function is implemented? You have to determine whether the local variables that are not destroyed are used in its implementation. So if you ask what features of JS are applied to the jquery code snippet in the beginning? Then it is just a call of anonymous and anonymous functions. However, it implies the closure feature and can implement the closure application at any time. Because JS is born with this feature! (This is just my understanding. I also want to know your understanding. Please contact us! We have the opportunity to create another independent topic for closures !)

Here, I apologize for the incorrect answer -- sorry...

Because this note is a collection of JS knowledge points derived from jquery, it may not work with the real JS learning. It is recommended that you first look at the Basic Books. However, the following chapters should be based on JavaScript. If you have any difficulty reading this article, you can check the following chapters first. Thank you for your support!

 

Http://blog.csdn.net/natineprince/archive/2009/11/02/4759533.aspx

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.