JS anonymous function declaration, call; JS closure detailed (reprint)

Source: Internet
Author: User

The code for the JS anonymous function is as follows :
(function () {
This ignores all implementations of JQuery
})();

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 debate on the forum- is this code not a closure? 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.

Function declaration (function  statement), to use a function, we must first declare its existence. The most common way is to use function  statement 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 parametric, even with a 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, js  interpreter will translate 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, Tip You abc  is a function  object. So what exactly is function  object?  
function  object  
function  objects are javascript , all functions are actually a function  object. With regard to this discussion, let's leave it to the next thematic section. Let's take a look, function  object can you directly use the constructor to create a new function? 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"

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:
Copy the 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 all functions, but they all have a feature --  No name. So we call them "  Anonymous functions  . However, just because they do not have "  , we have no way to find them. This extends the question of how to invoke an anonymous function.  
anonymous function calls  
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:  
Copy code code as follows :
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:
Copy the 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"

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 an anonymous function with a pair of parentheses, the fact that the parentheses are returned is an anonymous function.The Function object. 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.
Copy the code code as follows:
var abc=function (x, y) {return x+y;};/ /Assign an anonymous function object to theAbc
ABC'sconstructor and anonymous functions.constructor the same. 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 withA=function () {alert (1)} () is equivalent and cannot be connectedA= are removed. )
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? You look so sweaty....... Yes, me too (though I do know, just a question of ability to express). Let's move on to a simpler approach: closures, in fact, are a language feature, which refers to programming languages that allow functions to be treated as objects, and then define instance (local) variables in the function like they do in an object, and those variables can be saved to the instance object of the function in the function until it 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 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: 
Copy code code as follows :
var abc=function (y) { 
var x=y;//  This is the local variable  
return function () { 
Alert (x + +);//  is where the first-level function local variables in the closure feature are called x  and operate it  
Alert (y--);//  reference parameter variable is also a free variable }} (5);//  initialize  
ABC ();//"5" "5"  
ABC ();//"6" "4"  
ABC () ;//"7" "3"  
Alert (x);//  Error! "x"   undefined!  
See here, can you determine whether jquery  The code fragment is closed?  
in my understanding. 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 is the feature of js  applied? Then it's just an anonymous function and an anonymous function call. However, it implies closure characteristics and can be implemented at any time.

JS anonymous function declaration, call; JS closure detailed (reprint)

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.