


What is an anonymous function in JavaScript? Brief analysis of application scenarios
As the name suggests, anonymous functions refer to functions without names. They are used very frequently in actual development and are also the focus of learning JS well. The following article will give you a detailed introduction to anonymous functions in JavaScript. I hope it will be helpful to you!
##Anonymous function: A function without an actual name.
First we declare a normal function://声明一个普通函数,函数的名字叫fn function fn(){ console.log("web-chubby"); }
//匿名函数,咦,运行时,你会发现报错啦! function (){ console.log("web-chubby"); }
//匿名函数在其它应用场景括号可以省略 (function (){ //由于没有执行该匿名函数,所以不会执行匿名函数体内的语句。 console.log("web-chubby"); })
How to execute and use anonymous functions?
1. Execute anonymous functionIf you need to execute an anonymous function, just add a bracket after the anonymous function, that is, execute the function immediately- The parentheses only wrap the anonymous function followed by the execution parentheses (commonly used)
(function () { alert('匿名函数执行方式一') })();
- The parentheses will anonymous The function and the parentheses that execute the anonymous function are wrapped together to form an expression
(function (m) { alert(m) }('这是匿名函数传进来的参数'));
Application of anonymous functions
- When binding events Method
<input type="button" value="点我啊!" id="sub"> <script> //获得按钮元素 var sub=document.querySelector("#sub"); //给按钮增加点击事件。 sub.onclick=function(){ alert("当点击按钮时会执行到我哦!"); } </script>
- Function expression assigns an anonymous function to a variable
//将匿名函数赋值给变量fn。 var fn=function(){ return "我是一只小小小小留下,怎么飞也飞不高!" } //调用方式与调用普通函数一样 console.log(fn());//我是一只小小小小留下,怎么飞也飞不高!
- object The function attributes inside
var obj={ name:"web-chubby", age:18, fn:function(){ return "我叫"+this.name+"今年"+this.age+"岁了!"; } }; console.log(obj.fn());//我叫web-chubby今年18岁了!
- are callback functions, taking the anonymous function as one of the parameters
//过滤出值为9的值 let numArr = [1, 5, 9, 10] let newArr = numArr.filter(function (item) { if (item !== 9) { return item } });
- Function return value, that is, the function is used as a return value
//将匿名函数作为返回值 function fn(){ //返回匿名函数 return function(){ return "web-chubby"; } } //调用匿名函数 console.log(fn()());//web-chubby //或 var box=fn(); console.log(box());//web-chubby
Imitate block-level scope
Block Level scope, sometimes called private scope. There is no block-level scope in JavaScript. For example:if(1==1){//条件成立,执行if代码块语句。 var a=12;//a为全局变量 } console.log(a);//12 for(var i=0;i<3;i++){ console.log(i); } console.log(i);//4
(function(){ //这里是我们的块级作用域(私有作用域) })();
function fn(){ (function(){ var la="啦啦啦!"; })(); console.log(la);//报错---la is not defined } fn();
The role of anonymous functions:
1. Closure can be implemented through anonymous functions. Closure will be explained in the following articles. A quick introduction here: a closure is a function that can access variables defined within the function scope. To create a closure, you often need to use an anonymous function. 2. Simulate block-level scope and reduce global variables. After executing the anonymous function, the corresponding variables stored in the memory will be destroyed, thereby saving memory. Furthermore, in large-scale multi-person development projects, using block-level scope will greatly reduce the problem of naming conflicts, thereby avoiding catastrophic consequences. Developers no longer have to worry about messing up the global scope. [Related recommendations:The above is the detailed content of What is an anonymous function in JavaScript? Brief analysis of application scenarios. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

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

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.

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

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,

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

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.

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
