计算机网络/计算机科学与应用/系统/运维/开发

ES6第8回-箭头函数实践

<script>
        // 需求1  点击 div 2s后颜色变成 粉色
        // 获取元素 
        let  ad = document.getElementById('ad');
        // 绑定事件
        ad.addEventListener("click",function(){
            // 保存this的值
            // let _this = this; 之前的解决方案
            // 定时器
            //setTimeout(function(){
                // 修改背景颜色 this 
                // 之前的写法_this.style.background = 'pink';
            //},2000);
            // 变成箭头函数之后
            setTimeout(()=>{
                this.style.background = 'pink';
            },2000);
        })
        // 需求2  从数组中返回偶数的元素
        const arr = [1,6,9,10,100,25];
        // const result = arr.filter(function(item){
        //     if(item % 2 ===0){
        //         return true;
        //     }else{
        //         return false;
        //     }
        // });
        // 使用箭头函数
        const result = arr.filter(item => item % 2 === 0);
        console.log(result);
        
        // 箭头函数 适合与 this 无关的回调 定时器 数组的方法回调
        // 箭头函数不适合与this有关的回调  事件回调 对象的方法
    </script>


es6

微信小程序 https://www.javascriptcn.com/interview-weixinapp/677f48463d78df11d950b260.html

评论

^