Home > Web Front-end > JS Tutorial > body text

Analysis of creation and calling methods of anonymous functions in js_javascript skills

WBOY
Release: 2016-05-16 16:25:36
Original
1385 people have browsed it

This article analyzes the creation and calling methods of anonymous functions in js through examples. Share it with everyone for your reference. The specific implementation method is as follows:

An anonymous function is a function without a name, also called a closure function (closure), which allows you to temporarily create a function without a specified name. The value that is most often used as the parameter of the callback function (callback). Many novice friends do not understand anonymous functions. Let’s analyze it here.

function function name (parameter list) {function body;}

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

Because it is an anonymous function, there are generally no parameters passed to it.

Why create an anonymous function? Under what circumstances are anonymous functions used? There are two main common scenarios for anonymous functions, one is callback function, and the other is direct function execution.

Callback function, like asynchronous operation of ajax, requires callback function. I won’t explain it in detail here. Regarding the direct execution of functions, I can understand it by looking at an example:

Copy code The code is as follows:

In the above code, two alert boxes will be output sequentially. The content of the first alert box is b, and the second one is a. Have you seen any benefits? Yes, using functions to execute directly can limit the scope of variables, so that the same variables in different scripts can coexist.

Next, let’s first 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 commonly used way is to use the function statement to define a function, such as:

Copy code The code is as follows:
function abc(){
// code to process
}
function abc(){ // code to process }

Of course, your function can also take parameters or even return a value.

Copy code 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 will translate it into a Function object. For example, if you are defining the function number in one of the examples above, enter the following code:

Copy code The code is as follows:
alert(typeof abc);// "function"

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

Function object

Function object is an inherent object in JavaScript, and all functions are actually a Function object. Let's first see if the Function object can directly use the constructor to create a new function? The answer is yes. For example:

Copy code The code is as follows:
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 function

As the name suggests, an anonymous function is a function without an actual name. For example, let’s remove the name of the function in the above example and then determine whether it is a function:

Copy code 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 one characteristic - no name. So we call them "anonymous functions". However, just because they have no "name", we have no way to find 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:

Copy code 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 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 assign an anonymous function to its corresponding event reference.

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 another look at the following example:

Copy code 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 people may wonder why this method can be called successfully? 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.

Copy code The code is as follows:
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 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 instances can be defined in functions like operations in objects. (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 local variables defined in a programming language that allow code to call a running function.

Now let’s look at an example:

Copy code The code is as follows:
var abc=function(y){
var x=y;// This is a 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 operated on it
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!

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.

Most common usage:

Copy code The code is as follows:
(function() {
alert('water');
})();

Of course, you can also bring parameters:
Copy code The code is as follows:
(function(o) {
alert(o);
})('water');

Want to use chained calls to anonymous functions? Very simple:
Copy code The code is as follows:
(function(o) {
alert(o);
return arguments.callee;
})('water')('down');

You know all the common anonymous functions, let’s take a look at the uncommon ones:
Copy code The code is as follows:
~(function(){
alert('water');
})();//The writing is a bit cool~

void function(){
alert('water');
}();//It is said to be the most efficient~

function(){
alert('water');
}();

-function(){
alert('water');
}();

~function(){
alert('water');
}();

!function(){
alert('water');
}();

(function(){
alert('water');
}());//It feels a bit like enforcement~

I hope this article will be helpful to everyone’s JavaScript programming design.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!