箭头函数的实践与应用场景

复制代码
<!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>
<style>
    div{
        width: 200px;
        height: 200px;
        background: #58a;
    }
</style>
<body>
    <div id="ad"></div>
</body>
<script>
    // 需求1 点击div2s后颜色变为粉色
    let ad=document.getElementById('ad');
    ad.addEventListener("click",function(){
        // 这样写报错:Cannot set properties of undefined (setting 'background') 因为this指向的window
        // setTimeout(function(){
        //     //修改背景颜色 this
        //     this.style.background='pink';
        // })
        // 解决方案1
        // let _this=this;
        // setTimeout(function(){
        //     //修改背景颜色 this
        //     _this.style.background='pink';
        // })
        // 解决方案2
        setTimeout(()=>{
            //修改背景颜色 this
            this.style.background='pink';
        })
    },2000)
    // 从数组中返回偶数
    const arr=[1,4,6,87,34,56];
    const result=arr.filter(item=>item%2==0);
    console.log(result)
    // 箭头函数适合this无关的回调,定时器,数组的方法回调
    // 箭头函数不适合this有关的回调,事件回调,对象的方法
</script>
</html>
复制代码

 

<!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>
<style>
    div{
        width: 200px;
        height: 200px;
        background: #58a;
    }
</style>
<body>
    <div id="ad"></div>
</body>
<script>
    // 需求1 点击div2s后颜色变为粉色
    let ad=document.getElementById('ad');
    ad.addEventListener("click",function(){
        // 这样写报错:Cannot set properties of undefined (setting 'background') 因为this指向的window
        // setTimeout(function(){
        //     //修改背景颜色 this
        //     this.style.background='pink';
        // })
        // 解决方案1
        // let _this=this;
        // setTimeout(function(){
        //     //修改背景颜色 this
        //     _this.style.background='pink';
        // })
        // 解决方案2
        setTimeout(()=>{
            //修改背景颜色 this
            this.style.background='pink';
        })
    },2000)
    // 从数组中返回偶数
    const arr=[1,4,6,87,34,56];
    const result=arr.filter(item=>item%2==0);
    console.log(result)
    // 箭头函数适合this无关的回调,定时器,数组的方法回调
    // 箭头函数不适合this有关的回调,事件回调,对象的方法
</script>
</html>
posted @   鲁班大师智商二百五  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示