Learn and collect javascript anonymous function_javascript tips-js tutorial

Source: Internet
Author: User
I have been in touch with jQuery for a long time. I have too many questions about its implementation. I only know what it is, and I have no idea about its essence. Sadly! Therefore, it is necessary to study the principles. The Ancients "Teach fish, it is better to teach fish". Without a teacher, they can only learn "fish" by themselves. Let's start with something simple!
The following code is the most familiar, but do you know why? Why is the jQuery object introduced by adding the code to the page.

The Code is as follows:


(Function ($ ){
// Function implementation code
}) (JQuery );

I started from here! Programmers all know how to google and baidu. The same is true for me... Oh! It turns out that this is an anonymous function of javascript.

What is this anonymous function? Learn it slowly!
JavaScript defines a function in the following three methods:
1. function keyword (function) Statement:

The Code is as follows:


Function Name (){
Return;
}


2. Function Literals ):

The Code is as follows:


Var Name = function (){
Return;
}


3. Function () constructor:

Var Name = new Function ('A', 'Return ;')
The above three methods define the same method function Name. The second method is the most commonly used method. The last two methods copy a function to the variable Name, and the two functions have no names, is this an anonymous function? Let's take a look at the following explanation!

There is a difference between the literal number of functions and the Function () constructor!
(1 ). A Function is an anonymous Function. The syntax allows you to specify any Function name for a Function. When writing a recursive Function, you can call it yourself. If you use Function () to construct a Function, you cannot.

The Code is as follows:


Var f = function fact (x ){
If (x <= 1)
Return 1;
Else
Return x * fact (x-1 );
};


(2). Function () constructor allows dynamic creation and compilation of Javascript code during runtime. In this way, it is similar to the global function eval ().
(3). Function () constructor parses the Function body and creates a new Function object each time a Function is executed. Therefore, it is very inefficient to call Function () constructor in a loop or frequently executed Function. On the contrary, function literal is not re-compiled every time.
(4). When using Function () to construct a Function, it does not follow the typical scope. It always treats it as a top-level Function for execution.

The Code is as follows:


Var y = "global ";
Function constructFunction (){
Var y = "local ";
Return new Function ("return y"); // The local variable cannot be obtained.
}
Alert (constructFunction (); // output "global"


A name is also involved here, that is, the Function object. The Function object is an inherent object in JavaScript, and all functions are actually a Function object. Therefore, the three above are function objects.
The above can be summarized as: function objects can be created using common methods and constructor methods, and functions can also have no names (anonymous functions ).
To continue anonymous functions, as the name implies, anonymous functions are functions without actual names. For example, let's take the above example. Remove the function name, and then judge whether 2 or 3 is a function:

The Code is as follows:


Alert (typeof function () {}); // "function"
Alert (typeof function (a) {return a ;}); // "function"
Alert (typeof new Function ("a", "return a;") // "function"


All return function objects. It seems that there is no name but it is still a function. So how do we call an anonymous function?
To call a function, we must have a method to locate it and reference it. Therefore, we need to find a name for it. This is the role of 2, 3 "names" in this example. This is also the format we often see.
There is actually another way here, that is, the jQuery code just given, that is, to use () to enclose anonymous functions, and then add a pair of parentheses (including the parameter list ). Let's look at the code below!

The Code is as follows:


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


Many may wonder why this method can be called successfully? If you are not busy looking at the code segment, you may understand it.

The Code is as follows:


// Assign the anonymous function object to abc
Var abc = function (x, y) {return x + y ;};
Alert (abc). constructor = (function (x, y) {return x + y;}). constructor );
// 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.


If you think this application is still very strange, let's take a look at the explanation I have read online.
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 anonymous letters to 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.
Finally, let's look at the code mode of the anonymous function!
Error Mode: it cannot work, and the browser reports a syntax error.

Function () {alert (1 );}();
1. Function literal: first declare a function object and then execute it.
(Function () {alert (1 );})();
2. Priority expression: Since the Javascript Execution expression is from the inside of the parentheses to the outside, you can use parentheses to forcibly execute the declared function.
(Function () {alert (2 );}());
3. Void Operator: Use the void operator to execute a separate operand without parentheses.
Void function () {alert (3 );}()
These three methods are the same, and you can use them to look at your thoughts.
Haha! This is almost the same! This time, I understand that the first few jQuery statements are actually function literal!
(Anonymous function) (parameter) (function ($) {}) (jQuery );
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.