Research on the anonymous function of jquery

Source: Internet
Author: User

jquery Fragment:

?
123 (function(){//这里忽略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 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:

?
123 functionabc(){  // code to process}

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

?
123 functionabc(x,y){   returnx+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:

?
1 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:

?
12 varabc =  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:

?
123 alert(typeoffunction(){});// "function"alert(typeoffunction(x,y){returnx+y;});// "function"alert( typeofnewFunction("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:

?
1234 varabc= 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:

?
12 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.

?
123 varabc= function (x,y){ return x+y;}; // 把匿名函数对象赋给abc// abc的constructor就和匿名函数的constructor一样了。也就是说,两个函数的实现是一样的。alert((abc).constructor==( function (x,y){ returnx+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:

?
12345678910 varabc=function (y){varx=y;// 这个是局部变量returnfunction(){  alert(x++);// 就是这里调用了闭包特性中的一级函数局部变量的x,并对它进行操作  alert(y--);// 引用的参数变量也是自由变量}}(5);// 初始化abc();// "5" "5"abc();// "6" "4"abc();// "7" "3"alert(x);// 报错!“x”未定义!

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!

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.