Home Web Front-end JS Tutorial Detailed explanation of Javascript anonymous functions

Detailed explanation of Javascript anonymous functions

Jan 24, 2017 pm 01:59 PM
javascript anonymous function

Anonymous function is a function that is dynamically declared at runtime. They are called anonymous functions because unlike ordinary functions, they do not have function names.

Anonymous functions are defined through function expressions rather than function declaration syntax. You can create a new function using a function expression anywhere you can place an expression. For example, you can define a new function as an argument to a function call or as a property of another object.

The following is a typical named function:

function flyToTheMoon()
{
    alert("Zoom! Zoom! Zoom!");
}
flyToTheMoon();
Copy after login

The following is the same example but this time created as an anonymous function:

var flyToTheMoon = function()
{
    alert("Zoom! Zoom! Zoom!");
}
flyToTheMoon();
Copy after login


Anonymous functions are created by function expressions

The two most common ways to create functions in JavaScript are Utilize function declaration syntax and function expressions. Anonymous functions are created through function expressions.

If the function keyword appears first in a statement and is followed by a function name, then the function is created by the function declaration syntax:

Detailed explanation of Javascript anonymous functions

If If the function keyword appears elsewhere, it is most likely being used as a function expression:

Detailed explanation of Javascript anonymous functions

When a function expression is called, it creates a new function object and Return it. Here is an example of creating a function and assigning it to a variable called flyToTheMoon:

var flyToTheMoon = function() {
    alert("Zoom! Zoom! Zoom!");
}
Copy after login

The assignment here is almost the same as assigning the return value of any function to a variable, the only special thing is this The value is a function object rather than some simple number or date.

This is possible because functions are just a special kind of objects in javascript. This means they can be used like other objects. They can be stored in variables, passed as arguments to other functions, or returned by return statements within functions. Functions are always objects, no matter how they are created.

Once the function is stored in a variable, the variable can be used to call the function:

flyToTheMoon();
Copy after login


Anonymous functions are created at runtime

Function expressions can be used anywhere an expression can be placed. For example, you can use a function expression when a variable is assigned a value, when an argument is passed to a function, or in a return statement. This is possible because functions are always called at runtime.

The function declaration syntax is different. They run before any other code is executed because functions do not need to be declared before being called by the code.

Function declaration syntax cannot be used to create anonymous functions because they require the function to have a name. Function declaration syntax uses the function name to add it as a variable to the current scope.


Anonymous functions do not require a function name

This seems It's a bit strange, because how do you call a function without a name? This works because the function name is a bit different from the variable holding the function object.

A function created by the function declaration syntax will always have a function name and an identical function variable, because the function declaration syntax will automatically create this variable:

function flyToTheMoon() {
    alert("Zoom! Zoom! Zoom!");
}
flyToTheMoon();
Copy after login

For functions created by function expressions , this name is optional. Many times, the name is not important to us, so we create anonymous functions without names, like this:

var flyToTheMoon = function() {
    alert("Zoom! Zoom! Zoom");
}
flyToTheMoon();
Copy after login

However, function expressions actually support setting function names if you wish. of. Here is the same function, but this time with a function name:

var flyToTheMoon = function flyToTheMoon() {
    alert("Zoom! Zoom! Zoom");
}
flyToTheMoon();
Copy after login

Giving your function a name does not automatically add a variable named after the function name to the scope. You still need to assign the return value of the function expression to a variable.

In the previous example, the variable that holds the function object has the same name as the function, but this is not necessary: ​​

var thingsToDoToday = function flyToTheMoon() {
    alert("Zoom! Zoom! Zoom");
}
thingsToDoToday();
Copy after login


##Why do we need a name?

The name of a function can be used to call itself from within the function. This is useful in recursive functions.

var thingsToDoToday = function flyToTheMoon() {
    if(!onTheMoon)
        flyToTheMoon();
    else
        alert("One small step for a man..");
}
thingsToDoToday();
Copy after login
This is also useful for debugging because you can see the function name in the call stack. Usually anonymous functions look the same in the call stack. If you're faced with a nasty debugging situation, sometimes giving the function of interest a name can make the problem clearer.



##Why are anonymous functions useful?

There is no need to set a name for the anonymous function just for convenience. After all, the name of the function is not important in many cases. In most cases both anonymous and named functions work well for most tasks.

Functions created by function expressions are sometimes very useful.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

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.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Can Golang anonymous functions return multiple values? Can Golang anonymous functions return multiple values? Apr 13, 2024 pm 04:09 PM

Yes, anonymous functions in Go language can return multiple values. Syntax: func(arg1,arg2,...,argN)(ret1,ret2,...,retM){//Function body}. Usage: Use the := operator to receive the return value; use the return keyword to return multiple values.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Python Lambda Expressions: Making Programming Easier Python Lambda Expressions: Making Programming Easier Feb 19, 2024 pm 09:54 PM

A python Lambda expression is a small anonymous function that stores an expression in a variable and returns its value. Lambda expressions are often used to perform simple tasks that can be accomplished by writing a separate function, but Lambda expressions can make the code more concise and readable. The syntax of a Lambda expression is as follows: lambdaarguments: expressionarguments is the parameter list received by the Lambda expression, and expression is the body of the Lambda expression, which contains the code that needs to be executed. For example, the following Lambda expression adds two numbers and returns their sum: lambdax,

Python Lambda expressions: abbreviated, concise, powerful Python Lambda expressions: abbreviated, concise, powerful Feb 19, 2024 pm 08:10 PM

pythonLambda expressions are a powerful and flexible tool for creating concise, readable, and easy-to-use code. They are great for quickly creating anonymous functions that can be passed as arguments to other functions or stored in variables. The basic syntax of a Lambda expression is as follows: lambdaarguments:expression For example, the following Lambda expression adds two numbers: lambdax,y:x+y This Lambda expression can be passed to another function as an argument as follows: defsum( x,y):returnx+yresult=sum(lambdax,y:x+y,1,2)In this example

Python Lambda expressions: Uncovering the power of anonymous functions Python Lambda expressions: Uncovering the power of anonymous functions Feb 24, 2024 am 09:01 AM

Lambda expression in python is another syntax form of anonymous function. It is a small anonymous function that can be defined anywhere in the program. A lambda expression consists of a parameter list and an expression, which can be any valid Python expression. The syntax of a Lambda expression is as follows: lambdaargument_list:expression. For example, the following Lambda expression returns the sum of two numbers: lambdax,y:x+y. This Lambda expression can be passed to other functions, such as the map() function: numbers=[ 1,2,3,4,5]result=map(lambda

JavaScript and WebSocket: Building an efficient real-time search engine JavaScript and WebSocket: Building an efficient real-time search engine Dec 17, 2023 pm 10:13 PM

JavaScript and WebSocket: Building an efficient real-time search engine Introduction: With the development of the Internet, users have higher and higher requirements for real-time search engines. When searching with traditional search engines, users need to click the search button to get results. This method cannot meet users' needs for real-time search results. Therefore, using JavaScript and WebSocket technology to implement real-time search engines has become a hot topic. This article will introduce in detail the use of JavaScript

See all articles