(function(){
//Ignore all jQuery implementations here
})();
(function(){ //Ignore all implementations of jQuery here})();
When I first came into contact with jQuery half a year ago, I was like other people I am also very excited to see what the source code looks like. However, the first time I saw the source code, I was confused. Why can there be a function library like jQuery when there is only one anonymous function and no one sees it running (of course it is running...)? So, I came to CSDN with questions. As a result, I believe many people are very clear about it now (because there are many others coming after me, haha~). When an anonymous function is enclosed in parentheses and then followed by parentheses, the anonymous function can be run immediately! How amazing!
Hehe! So much for the nonsense. In this section, the jQuery snippet we encountered is a set of anonymous functions that run immediately. This usage has also caused heated debates on forums - does this code belong to a closure? With this question in mind, we start from 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 conducive to the implementation of our applications, it is desirable - black cats and white cats, the one that catches mice is a good cat!)
To talk about anonymous functions, we must first start with the function itself. The definition of a function is 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 similar. Because we all know that a function in a computer is similar to the description in the mathematical definition. It is a set of code combination blocks that process some input data through logical operations set by the code and return a unique output. ——Of course, the special case is that the input data is empty or the output data is empty, or both are empty.
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 function statements is to define a function, such as:
function abc(){
// code to process
}
function abc(){ // code to process }
Of course, your function can also be With parameters, even with return values.
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 will translate it into a Function object. For example, if you are defining the function number in one of the examples above, and then enter the following code:
alert(typeof abc);// "function"
Your browser will pop up a prompt box, prompting Your abc is a Function object. So what exactly is a Function object?
Function object
Function object is an inherent object in JavaScript. All functions are actually a Function object. We leave the discussion of this aspect to the next topic section. Let's first see if the Function object can directly use the constructor to create a new function? The answer is yes. For example:
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 an understanding of how to declare a function. So what is an anonymous function?
Declare anonymous functions
As the name suggests, anonymous functions are functions without actual names. For example, let’s remove the name of the function in the above example and then determine whether it is a function:
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 one feature - no name. So we call them "anonymous functions". However, just because they don’t have “names,” we have no way of finding them. This leads to the question of how to call an anonymous function.
Call of anonymous function
To call 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:
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 actually equivalent to defining the function in another way. This usage is something we encounter more frequently. For example, when we set a DOM element event handling function, we usually do not give them a name, but give its corresponding event reference an anonymous function.
There is actually another way to call anonymous functions, which is the jQuery fragment we saw - using () to enclose the anonymous function, and then add a pair of parentheses (including the parameter list). Let’s take a look at the following example again:
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 called successfully Woolen cloth? For those who think this application is strange, please read my explanation below.
Do you know the function of parentheses? Parentheses can divide our expression combination 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 use a pair of parentheses to surround an anonymous function, what the pair of parentheses actually returns is a Function object of the anonymous function. Therefore, a pair of parentheses plus an anonymous function is referenced by us just like a named function. So if you add a parameter list after this reference variable, the calling form of an ordinary function will be achieved.
I don’t know if you can understand the above textual expression. If you still can’t understand it, try looking at the following code.
var abc=function(x,y){return x y ;};// Assign the anonymous function object to abc
// The constructor of abc 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);
var abc=function(x,y){return x y;};// The anonymous function object is assigned to abc // The constructor of abc 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 objects. That is, the function body represented by the function object.
In short, understand it (the anonymous function enclosed by parentheses) as the function object returned by the parentheses expression, and then you can make a normal parameter list call to this function object. (I made a mistake here before. You cannot directly call a function with only a function expression. Removing the anonymous function brackets must be accompanied by assigning the expression. That is, (function(){alert(1)})() should be the same as a =function(){alert(1)}() is equivalent, you cannot remove a=. )
Closure
What is a closure? Closure refers to a code block in a certain programming language that allows a first-level function to exist and the free variables defined in the first-level function cannot 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? You must be sweating after watching it... It's okay, me too (although I understand it, it's just a matter of my ability to express myself). Let's explain it in a simpler way: closure is actually a language feature. It refers to a programming language that allows functions to be treated as objects, and then operations like operations in the object can be moved to define instances in the function. (local) variables, and these variables can be saved in the function until the instance object of the function is destroyed. Other code blocks can obtain the values of these instance (local) variables in some way and extend the application.
I don’t know if it will be clearer after explaining it this way. If you still don’t understand, let’s simplify it again: closure actually refers to a local part defined in a programming language that allows code to call a running function. variable.
Now let’s look at an example:
var abc=function(y){
var x=y;// This is a local variable
return function(){
alert(x );// This is where one of the closure features is called Level function local variable // "5" "5"
abc();// "6" "4"
abc();// "7" "3"
alert(x);// Error! "x" is not defined!
var abc=function(y){ var x=y;// This is the local variable return function(){ alert(x);// This is where the x of the first-level function local variable in the closure feature is called , and operate on it 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!
Seeing this, can you tell whether the jQuery code snippet is closed?
Let’s use my understanding. Whether the closure feature is applied, you must determine whether the code has the most important element: local variables that have not been destroyed. Then it is obvious that an anonymous function without any implementation cannot apply the closure feature. But what if there is an implementation in the anonymous function? Then you have to make sure whether any local variables that have not been destroyed are used in its implementation. So if I ask you what features of JS are used in the jQuery code snippet in the opening article? Then it's just anonymous functions and anonymous function calls. However, it implies the properties of closures, and closures can be applied 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, if you have the opportunity, let’s open another topic independently!)