Home Web Front-end JS Tutorial A closer look at anonymous functions and arrow functions in JavaScript

A closer look at anonymous functions and arrow functions in JavaScript

Nov 03, 2023 pm 06:05 PM
javascript anonymous function arrow function

A closer look at anonymous functions and arrow functions in JavaScript

In JavaScript, functions are first-class citizens, which means they can be passed, stored, and called just like variables. Anonymous functions and arrow functions are two commonly used function forms in JavaScript.

Anonymous functions are functions without names, usually declared through function expressions. It is created at declaration time but can only be used at the declaration location. Anonymous functions can be passed directly as function parameters or stored as a variable that can be called.

For example, we can use the following anonymous function to create an immediate execution function:

(function () {
  console.log('立即执行函数。');
})();
Copy after login

(function () {})() in the code represents an anonymous A function that contains a block of code that prints out a message. It is used to create an immediate execution function, that is, it will run immediately after declaration. This function does not require a global name, so we can declare it as an anonymous function.

Compared with anonymous functions, arrow functions are a new feature in ES6. Arrow functions are a simpler way to declare functions, using => symbols to connect the parameter list and function body. Arrow functions can directly return the value of an expression.

The following is a simple example that shows how to use arrow functions to print out a message:

const printMessage = message => console.log(`信息为: ${message}`);
printMessage('Hello World!');
Copy after login

const printMessage = message => console.log(The information is: ${message}); represents an arrow function, which receives a parameter message and prints this parameter to the console. We then store this arrow function into a variable printMessage and use it to print out a message.

Another difference is that in an arrow function, the scope of this is the context in which the function that has it is defined, not the context in which it is executed. This causes this to not work as expected in some special cases (such as requiring dynamic binding context) when using arrow functions. In this case, using an anonymous function may be more useful.

Here is a classic example of using arrow functions in an object literal resulting in incorrect context for this:

const person = {
  name: 'John Doe',
  getName: () => {
    console.log(this.name); // undefined
  }
};
person.getName();
Copy after login

Here, we define An object containing a property name and a method getName. The getName method is an arrow function that attempts to print the value of this.name. However, because the arrow function uses the context in which the function that has it is defined, the value of this.name is undefined. In this case it would be better to use an anonymous function.

Here is the same example, this time we use an anonymous function instead of an arrow function:

const person = {
  name: 'John Doe',
  getName: function () {
    console.log(this.name); // John Doe
  }
};
person.getName();
Copy after login

Here, we just convert the arrow function into an anonymous function. This function uses the normal function context, so the value of this.name is the correct value.

In general, anonymous functions and arrow functions are two commonly used function forms in JavaScript but have different characteristics. When using functions, you need to choose the appropriate function form according to the actual situation.

The above is the detailed content of A closer look at anonymous functions and arrow functions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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

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

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.

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,

What is the difference between lambda expressions and anonymous functions? What is the difference between lambda expressions and anonymous functions? Apr 17, 2024 pm 03:18 PM

Lambda expressions and anonymous functions are both ways of creating anonymous functions in Python, but there are differences. Assignment method: lambda expression returns a function, and anonymous functions must be assigned to variables to be used. Code complexity: A lambda expression can only contain one expression, while an anonymous function can contain multiple statements.

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

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

See all articles