Home Web Front-end JS Tutorial What is an anonymous function in JavaScript? Brief analysis of application scenarios

What is an anonymous function in JavaScript? Brief analysis of application scenarios

Aug 04, 2022 pm 01:10 PM
javascript anonymous function

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!

What is an anonymous function in JavaScript? Brief analysis of application scenarios

##Anonymous function: A function without an actual name.

First we declare a normal function:

//声明一个普通函数,函数的名字叫fn
function fn(){
    console.log("web-chubby");
}
Copy after login

Then remove the name of the function to become an anonymous function:

//匿名函数,咦,运行时,你会发现报错啦!
function (){
    console.log("web-chubby");
}
Copy after login

At this point, you will find When running an anonymous function alone, an error is reported because it does not meet the syntax requirements!

What is an anonymous function in JavaScript? Brief analysis of application scenarios

Solution: Just wrap a bracket around the anonymous function to make it an expression:

//匿名函数在其它应用场景括号可以省略
(function (){
    //由于没有执行该匿名函数,所以不会执行匿名函数体内的语句。
    console.log("web-chubby");
})
Copy after login

How to execute and use anonymous functions?

1. Execute anonymous function

If 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('匿名函数执行方式一')
    })();
    Copy after login
  • The parentheses will anonymous The function and the parentheses that execute the anonymous function are wrapped together to form an expression

2. Anonymous function parameter passing

is the same as other ordinary parameters. Just write the parameters directly within the brackets:

 (function (m) {
      alert(m)
    }('这是匿名函数传进来的参数'));
Copy after login

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>
    Copy after login
  • Function expression assigns an anonymous function to a variable

  • //将匿名函数赋值给变量fn。
    var fn=function(){
        return "我是一只小小小小留下,怎么飞也飞不高!"
    }
    //调用方式与调用普通函数一样
    console.log(fn());//我是一只小小小小留下,怎么飞也飞不高!
    Copy after login
  • 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岁了!
    Copy after login
  • 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
          }
        });
    Copy after login
  • 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
    Copy after login

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
Copy after login

if(){}for(){}, etc. do not have their own scope. If it goes out of its own scope, the declared variable will be destroyed immediately. But we can simulate block-level scope through anonymous functions:

(function(){
    //这里是我们的块级作用域(私有作用域)
})();
Copy after login

Try block-level scope:

function fn(){
    (function(){
        var la="啦啦啦!";
    })();
    console.log(la);//报错---la is not defined
}
fn();
Copy after login

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:

javascript learning tutorial]

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!

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)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
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,

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

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.

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

See all articles