JavaScript匿名函数的典型用例是什么?


在本文中,我们将探讨JavaScript中的**匿名**函数,并学习它们的用例。匿名函数是一种特殊类型的函数,它没有任何名称与之关联。

JavaScript中,我们通常在定义任何JavaScript函数之前使用function <funcName>()关键字。但是,在JavaScript的匿名函数中,我们只使用function关键字来定义函数,而没有任何支持的名称。

创建匿名函数后无法访问它,只能通过将函数存储为值的变量来访问它。匿名函数可以有多个参数,但始终只执行单个表达式。

示例1

在下面的示例中,我们创建了一个普通函数,然后是一个简单的匿名函数。这两个函数执行相同的操作,即向控制台打印消息。但匿名函数没有函数名,只有一个表达式。

#文件名: index.html

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initialscale= 1.0" />
      <title>Anonymous Function</title>
   </head>
   <body>
      <h1 style="color: red;">
         Welcome To Tutorials Point
      </h1>
      <script>
         // Normal function
         function Display() {
            return "Welcome To Tutorials Point!";
         }
         console.log(Display());
         // Anonymous function
         let display = function() {
            return "SIMPLY EASY LEARNING!!!";
         }
         console.log(display());
      </script>
   </body>
</html>

输出

它将在控制台中产生以下输出。

Welcome To Tutorials Point!
SIMPLY EASY LEARNING!!!

示例2

在下面的示例中,我们使用箭头和不使用箭头创建了两个匿名函数。这两个函数都执行两个数字的加法运算。

#文件名: index.html

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initialscale= 1.0" />
      <title>Anonymous Function</title>
   </head>
   <body>
      <h1 style="color: red;">
         Welcome To Tutorials Point
      </h1>
      <script>
         // Anonymous Function
         let add = function (a, b) {
            return a + b;
         };
         console.log("Sum of 3 & 5 using Anonymous Function is:" + add(3,5));
         
         // Anonymous function using arrow
         let addV2 = (a, b) => a + b;
         console.log("Sum of 3 & 5 using Anonymous Function " + "with Arrow is:" + addV2(3,5));
      </script>
   </body>
</html>

输出

上述程序成功执行后,将在控制台中产生以下输出。

Sum of 3 & 5 using Anonymous Function is:8
Sum of 3 & 5 using Anonymous Function with Arrow is:8

更新于:2022年4月28日

411 次查看

启动你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.