在Js中匿名函数的几种写法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
       /*匿名函数的用法:*/

        // 1. 字面量形式
        let fn=function(){
            console.log("匿名函数赋值给变量,成为一个有名字的函数");
        }
        fn();//这样就是有名字的函数了

        // 2. 对象函数形式
        let obj={
            name:"小明",
            say:function(){
                console.log(this.name+"说:hello");
            }
        }
        obj.say(); // 小明说:hello

        // 3. 作为事件处理函数
         document.onclick=function(){
             console.log("我被点击了");
         }
  
         // 4. 作为回调函数
         function add(a,b,callback){
             let result=a+b;
             callback(result);
         }
         add(1,2,function(result){
             console.log("结果是:"+result);
         })

        function fn1(result){
             setTimeout(() => {
                console.log("我是主函数,被调用了");
                result();
             }, 2000);
           }
          fn1(function(){
             console.log("我是回调函数,被调用了");
          })

          //立即执行函数
          (function(){
             console.log("我是立即执行函数");
          }());

          //箭头函数
          let add1=(a,b)=>a+b;
          console.log(add1(1,2)); // 3

         
    </script>
</body>
</html>
posted @ 2024-10-05 14:25  一个人走在路上  阅读(0)  评论(0编辑  收藏  举报