Home Web Front-end JS Tutorial Analysis of creation and calling methods of anonymous functions in js_javascript skills

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

May 16, 2016 pm 04:25 PM
js create anonymous function method transfer

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.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. Mar 28, 2024 pm 12:50 PM

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

How to create a folder on Realme Phone? How to create a folder on Realme Phone? Mar 23, 2024 pm 02:30 PM

Title: Realme Phone Beginner’s Guide: How to Create Folders on Realme Phone? In today's society, mobile phones have become an indispensable tool in people's lives. As a popular smartphone brand, Realme Phone is loved by users for its simple and practical operating system. In the process of using Realme phones, many people may encounter situations where they need to organize files and applications on their phones, and creating folders is an effective way. This article will introduce how to create folders on Realme phones to help users better manage their phone content. No.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed! Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed! Mar 23, 2024 am 10:42 AM

In today's society, mobile phones have become an indispensable part of our lives. As an important tool for our daily communication, work, and life, WeChat is often used. However, it may be necessary to separate two WeChat accounts when handling different transactions, which requires the mobile phone to support logging in to two WeChat accounts at the same time. As a well-known domestic brand, Huawei mobile phones are used by many people. So what is the method to open two WeChat accounts on Huawei mobile phones? Let’s reveal the secret of this method. First of all, you need to use two WeChat accounts at the same time on your Huawei mobile phone. The easiest way is to

Usage and characteristics of C++ anonymous functions Usage and characteristics of C++ anonymous functions Apr 19, 2024 am 09:03 AM

An anonymous function, also known as a lambda expression, is a function that does not specify a name and is used for one-time use or to pass a function pointer. Features include: anonymity, one-time use, closures, return type inference. In practice, it is often used for sorting or other one-time function calls.

See all articles