Home Web Front-end JS Tutorial What is an anonymous function in JavaScript?

What is an anonymous function in JavaScript?

Apr 28, 2018 am 11:21 AM
js anonymous function

This article will introduce to you what anonymous functions are in JavaScript. I hope that after reading this article, you will have a certain understanding of the concept and use of anonymous functions in JavaScript.

What is an anonymous function in JavaScript?

#What is an anonymous function in JavaScript?

In front-end interviews, interviewers will basically ask what is an anonymous function and what is a closure function.

This article will first talk about what an anonymous function is.

Anonymous function, as the name implies, is a function without a name. Usually the functions we write are like this:

function do(){
  // 执行代码  
};
// 调用
do();
Copy after login

This way of writing is to define a function named do and pass the function name Make the call.

What would it be like if there was no name?

function () {
   // 执行代码   
 };
Copy after login

This way of writing will report an error during compilation:

Uncaught SyntaxError: Unexpected token (
Copy after login

Why is this? It turns out that when the browser performs syntax analysis, it finds that this function cannot be executed at all.

Then why do we need anonymous functions? If there is another coding method in a programming language, then this coding method will definitely run normally. So how to make the anonymous function run? Look at the following example:

var do = function () {  // 执行代码  }do();
Copy after login

Everyone must know this kind of function. In fact, this way of writing is to copy the anonymous function into the variable do, and then execute the function through the variable name.

(function(){   // 执行代码 
  console.log("打印成功");
})();
Copy after login

What does the above code mean?

You can first divide the above code into several parts:

The first part is the anonymous function inside the brackets, the second part is the anonymous function with brackets, and the third part with The parentheses used at the end of the execution.

The anonymous function inside the brackets can be regarded as treating the anonymous function as a variable and then executing it through the brackets.

(function () {
   // 执行代码 
})();

// 相当于
var do = function() {
   // 执行代码  
};

do();
Copy after login

In fact, the above anonymous function writing method is used in many places. This type is also called a self-executing function. Some toolkits such as JQuery will use this writing method. What are the advantages of self-executing functions? ?

// 定义一个全局变量a
var a = 1;

(function() {
  // 在自执行函数中也创建一个变量a
  var a = 2;
   console.log(a);  // 2
})();

console.log(a); // 1
Copy after login

You can see that the number printed in the self-executing function is 2, while the number printed in the self-executing function is 1;

Why is this?

Because there is a name in the program called scope, the scope of the global environment is called the global scope, the scope in the function is called the function scope, and the scope is hierarchical, internal scope Variables in the outer scope can be accessed in the domain, but variables in the inner scope cannot be accessed in the outer scope.

When accessing a variable in an internal scope, it will first search in the scope where it is located. If it cannot be found, it will search in the upper-level scope. If it cannot find it, it will search higher up again. to find the global scope. This layer-by-layer relationship is like a chain, so it is called a scope chain.

Look at the above code again: in the self-executing function, the console.log function accesses the a variable. It first searches in its own scope and finds the a variable, so the value of a is output 2; the global environment The console.log function in also accesses the a variable. Since the external scope cannot access the internal scope, the a variable accessed in the global environment can only be searched in the global function environment, so the value of a is 1;

Summary: The advantage of a self-executing function is to ensure that the variables in the self-executing function will not be contaminated by other environments.

This article comes from the js tutorial column, welcome to learn!

The above is the detailed content of What is an anonymous function 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)

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

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

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.

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

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,

See all articles