7.箭头函数的实践

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      div {
        width: 200px;
        height: 200px;
        background: #56a;
      }
    </style>
  </head>
  <body>
    <div id="d1"></div>

    <script>
      let d1 = document.getElementById("d1");
      d1.addEventListener("click", function () {
        //这里不能用箭头函数,需要this指向当前的d1元素,而写了箭头函数this会指向window
        // 保存this的值
        // _this = this;
        // setTimeout(function () {
        //   _this.style.background = "pink";   //之前的写法,因为this在这里指向window,所以要提前保存this的值
        // }, 3000);
        // setTimeout(() => {
        //   this.style.background = "pink"; //箭头函数写法,this指向外部定义的地方
        // }, 300);
      });
      let arr = [1, 2, 3, 4, 5, 6, 7];
      let result = arr.filter((item) => item % 2 === 0);
      console.log(result);

      // 箭头函数适合与this无关的回调:定时器,数组的方法回调
      // 箭头函数不适合与this有关的回调,事件回调,对象的方法
    </script>
  </body>
</html>
posted @   问某完红  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示