js anonymous function

Query fragment:

  1. (function(){  
  2. //Ignore all implementations of jQuery here  
  3. })();  

  When I first got my hands on jQuery half a year ago, I was as excited as anyone to see what the source code looked like. However, at first glance at the source code, I was confused. Why is there only one anonymous function that does not see the operation (of course it is running...), so there is a function library like jQuery? So, I came to CSDN with doubts. As a result, I believe that many people are very clear now (because there are no shortage of comers after me, hehe~). When an anonymous function is enclosed in parentheses, the anonymous function will run immediately! It's amazing!

  Hey-hey! Bullshit so far. The jQuery snippet we encountered in this section is a set of anonymous functions that run immediately. And this usage has also caused a heated debate on the forum - does this code belong to a closure? With this question in mind, we start with the basics, analyze each key element, and find our own answer. (Yes, my own answer! In my opinion, all theories are just forms, as long as it is beneficial to our application implementation, it is desirable - a black cat is a white cat, and the cat that catches the mouse is a good cat!)

  To talk about anonymous functions, we must first 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 computer programming languages, the definitions of functions are also closely related. 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 return a unique output after processing some input data through the logical operation set by the code. - The special case, of course, is that the input data is empty or the output data is empty, or both.

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

  • function declaration (function statement)

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

  1. function abc(){  
  2.   // code to process  
  3. }  

   Of course, your functions can also take parameters and even return values.

  1. function abc(x,y){  
  2.   return x+y;  
  3. }  

  However, no matter how you define your function, the JS interpreter will translate it into a Function object. For example, you are defining the function number of one of the examples above, and then 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 exactly is a Function object?

  • Function object

  The Function object is an inherent object in JavaScript, and all functions are actually a Function object. We will leave the discussion of this aspect to the next thematic section. Let's see first, can the Function object directly use the constructor to create a new function? The answer is yes. E.g:

  1. var abc = new Function("x","y","return x*y;");  
  2. alert(abc(2,3)); // "6"  

  I believe that everyone should now have an understanding of how to declare a function. So what is an anonymous function?

  • declare anonymous function

  As the name suggests, an anonymous function is a function without an actual name. For example, let's remove the name of the function in the above example, and then judge 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 one feature - no names. So we call them "anonymous functions". However, just because they don't have a "name", we have no way of finding them. This leads to the question of how to call an anonymous function.

  • anonymous function call

  To call a function, we must have a way to locate it, to reference it. So, we will need to help it find a name. E.g:

  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 functions in a different way. This usage is what we encounter more frequently. For example, when we set an event handler for a DOM element, we usually do not name them, but assign an anonymous function to their corresponding event reference.

  There is actually another way to call anonymous functions, which is the jQuery fragment we saw - use () to enclose the anonymous function, and then add a pair of parentheses (containing the parameter list). Let's look at the following example again:

  1. alert((function(x,y){return x+y;})(2,3));// "5"  
  2. alert((new Function("x","y","return x*y;"))(2,3));// "6"  

  Many people may wonder why this method can be successfully called? For those of you who find this app strange, just read my explanation below.

  Do you know the function of parentheses? Parentheses can combine our expressions into blocks, 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. Therefore, when we enclose an anonymous function with a pair of parentheses, in fact, what the parentheses return is the Function object of an anonymous function. Therefore, a pair of parentheses plus an anonymous function gets us its reference position just like a function with a name. So if you add a parameter list after this reference variable, you will achieve the normal function call form.

  I don't know if you can understand the above text expression. If you still can't understand it, look at the following code and try it again.

  1. var abc=function(x,y){return x+y;};// Assign anonymous function object to abc  
  2. // The constructor of abc is the same as the constructor of anonymous functions. That is, 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 that creates the object. That is, the function body represented by the function object.

  In short, understand it (an anonymous function enclosed by parentheses) as the function object returned by the parenthesis expression, and then you can make a normal parameter list call to this function object. (A mistake was made here. Only function expressions cannot directly call functions. Removing anonymous function parentheses must be accompanied by assignment of expressions. That is, (function(){alert(1)})() should be combined with a =function(){alert(1)}() is equivalent, you cannot even remove a=.)

  • Closure

   What is a closure? A closure refers to a code block in a certain programming language that allows the existence of a first-level function and the free variables defined in the first-level function can be released. Until the first-level function is released, these unused variables can also be applied outside the first-level function. Free variables released.

  how? Look at it and sweat it... It's okay, so am I (although I understand it, it's just a matter of expressing ability). Let's change it to a simpler method: Closures are actually a language feature. It refers to a programming language that allows functions to be regarded as objects, and then can be moved like operations in objects to define instances in functions. (local) variables, and these variables can be saved in the function until the instance object of the function is destroyed, and other code blocks can obtain the values ​​of these instance (local) variables in some way and apply extensions.

  I don’t know if it will be clearer after explaining it this way. If it is still unclear, then let’s simplify it again: Closures actually refer to local variables defined in a programming language that allow code to call a function that has already been run.

  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 where the x of the first-level function local variable in the closure feature is called and operated on  
  5.   alert(y--); // The referenced parameter variable is also a free variable  
  6. }}(5); // Initialize  
  7. abc();// "5" "5"  
  8. abc();// "6" "4"  
  9. abc();// "7" "3"  
  10. alert(x); // report an error! "x" is undefined!  

  Seeing this, can you judge whether the jQuery code snippet is a closure?

  In my understanding. Whether or not the closure feature is applied, it must be determined whether the piece of code has the most important element: local variables that are not destroyed. Then obviously, an anonymous function without any implementation can't apply the closure feature. But what if there is an implementation in the anonymous function? It also has to determine whether its implementation uses those local variables that are not destroyed. So if I ask you what feature in JS is applied to the jQuery code snippet in the opening paragraph? Then it's just an anonymous function and an anonymous function call. However, it implies the properties of closures, and closure applications 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! Regarding closures, there is a chance to open another topic independently!)

 

Guess you like

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