Create and call methods of anonymous functions in js

Source: Internet
Author: User

Create and call methods of anonymous functions in js

An anonymous function is a function without a name. It is also called a closure function (closures). A function without a specified name can be created temporarily. The value that is most often used as the callback function parameter. Many new users do not know about anonymous functions. Here we will analyze it.

Function Name (parameter list) {function body ;}

If you create an anonymous function, it should be:
Function () {function body ;}

Because it is an anonymous function, there is usually no parameter passed to it.

Why create an anonymous function? Under what circumstances will anonymous functions be used. Anonymous functions are commonly used in two scenarios: callback and direct execution.

Callback functions, such as ajax asynchronous operations, need callback functions. I will not explain it here. For direct function execution, I can see the following example:

The Code is as follows:

<Script language = "javascript">
Var a = "";
(Function (){
Var a = "B ";
Alert ();
})();
Alert ();
</Script>


In the above Code, two alert boxes are output sequentially. The content of the First alert box is B, and the second is. Do you see any benefits? Yes. Using a function to directly execute a variable can limit the scope of the variable so that the same variables in different scripts can coexist.

 

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

To use a function, you must first declare its existence. The most common method is to use a function statement to define a function, such:

The Code is as follows:

Function abc (){
// Code to process
}
Function abc () {// code to process}

 

Of course, your function can also contain parameters or even return values.

The Code is as follows:

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 translates it into a Function object. For example, if you define the function number of one of the above examples, enter the following code:

The Code is as follows:

Alert (typeof abc); // "function"

 

Your browser will pop up a prompt box prompting you that abc is a Function object. So what is a Function object?

Function object

Function objects are inherent objects in JavaScript. All functions are actually Function objects. Let's first look at whether the Function object can directly use the constructor to create a new Function? The answer is yes. For example:

The Code is as follows:

Var abc = new Function ("x", "y", "return x * y ;");
Alert (abc (2, 3); // "6"


I believe you have some knowledge about how to declare a function. So what is an anonymous function?

 

Declare anonymous Functions

As the name implies, an anonymous function is a function without a real name. For example, we can remove the name of the function in the above example and determine whether it is a function:

The Code is 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, we cannot find them because they do not have a "name. This raises the question of how to call an anonymous function.

Call of anonymous Functions

To call a function, we must have a method to locate it and reference it. Therefore, we need to find a name for it. For example:

The Code is as follows:

Var abc = function (x, y ){
Return x + y;
}
Alert (abc (2, 3); // "5"

 

The above operation is actually equivalent to defining a function in another way. This usage is frequently encountered. For example, when we set a DOM element event processing function, we usually do not set their names, but assign the corresponding event to reference an anonymous function.

There is also another way to call an anonymous function, that is, the jQuery snippet we see -- use () to enclose an anonymous function, and then add a pair of parentheses (including the parameter list ). Let's take a look at the following example:

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 this application is strange, let's take a look at the following explanation.

Do you know the role of parentheses? 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 an anonymous function to the 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.

I don't know if you can understand the above text. If you still can't understand it, let's try the following code again.

Copy the Code as follows:

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

 

PS: constructor refers to the function for creating objects. That is, the function body represented by the function object.
In short, it is understood as the function object returned by the parentheses expression (the anonymous function included in the parentheses), and then the function object can be called as a normal parameter list. (The preceding error is reported. Only function expressions cannot directly call functions. To remove Anonymous function brackets, you must assign values to the expressions. That is, (function () {alert (1)}) () should be equivalent to a = function () {alert (1, cannot even remove a = .)

Closure

What is a closure? A closure refers to a code block in a programming language that allows a level-1 function to exist and the free variables defined in the level-1 function cannot be released until the level-1 function is released, these unreleased free variables can also be applied to a level-1 function.

How? See a sweat ...... It's okay, so do I (although I understand it, it's just a matter of expression ability ). Let's change to a simpler method: closure is actually a language feature. It refers to a programming language that allows functions to be viewed as objects, then, you can define instance (local) variables in the function as you operate in the object. These variables can be saved to the function until the Instance Object of the function is destroyed, other code blocks can get the value of these instance (local) variables in some way and perform application extension.

I don't know whether it will be clearer after this explanation. If I still don't understand it, Let's simplify it: closure, actually, it refers to the local variables defined in the function that can be called by the code in the program language.

Now let's look at an example:

Copy the Code as follows:

Var abc = function (y ){
Var x = y; // This is a local variable.
Return function (){
Alert (x ++); // This is the x of the local variable of the first-level function in the closure feature.
Alert (y --); // The referenced parameter variable is also a free variable.
} (5); // Initialization
Abc (); // "5" "5"
Abc (); // "6" "4"
Abc (); // "7" "3"
Alert (x); // error! "X" is not defined!


Can you determine whether the code snippet of jQuery is closed?

 

Let me understand it. Whether the closure feature is applied, you must determine whether the Code contains the most important elements: local variables not destroyed. Obviously, the closure feature cannot be applied without any implemented anonymous functions. But what if an anonymous function is implemented? You have to determine whether the local variables that are not destroyed are used in its implementation. So if you ask what features of JS are applied to the jQuery code snippet in the beginning? Then it is just a call of anonymous and anonymous functions. However, it implies the closure feature and can implement the closure application at any time.

The most common usage:

The Code is as follows:

(Function (){
Alert ('water ');
})();


You can also include the following parameters:

The Code is as follows:

(Function (o ){
Alert (o );
}) ('Water ');


Function chain call? Simple:

Copy the Code as follows:

(Function (o ){
Alert (o );
Return arguments. callee;
}) ('Water') ('low ');


Common anonymous functions are all known. See the following:

The Code is as follows:

~ (Function (){
Alert ('water ');
}) (); // It's cool to write ~
 
Void function (){
Alert ('water ');
} (); // It is said that the efficiency is the highest ~
 
+ Function (){
Alert ('water ');
}();
 
-Function (){
Alert ('water ');
}();
 
~ Function (){
Alert ('water ');
}();
 
! Function (){
Alert ('water ');
}();
 
(Function (){
Alert ('water ');
} (); // A bit forced to execute ~

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.