2021-06-10

箭头函数实践

#箭头函数实践

<style>
    div {
        width:200px;
        height:200px;
        background:#baf;
    }
</style>


<div id='ad'>
    <script>
        // 1、需求:点击 div 之后两秒颜色发生改变
        //获取元素
        let ad = document.getElementById('ad');
        //绑定事件
        ad.addEventListener("click",function(){
            //设置一个定时器
            //  (使用 _this 保存此时 function 的this)
            //(var _this = this;)
            setTimeout(function(){
                //修改背景颜色
                //如果直接没有上边的 _this = this; 会报错,this 指向 window
                // _this.style.background = 'pink';
            },2000)


            //但是可以使用就按头函数更加方便一点
            setTiemOut(() => {
                //修改背景颜色
                this.style.background = 'pink';},2000)
        })
    </script>

</div>

这是因为在箭头函数下, this是静态的 其指向的是在声明时候的作用域。上述的箭头函数的 this 指向的是 function 。

function 的事件源是 ad 所以 箭头函数 里面的 this 就指向了 ad 本身。

需求二

从数组中返回偶数的元素

//使用原来的方法
const arr = [1,6,9,10,100,25];
const result = arr.filter(function( item ){
    if(item % 2 ===0){
        return true; 
    }else{
        return false;
    }
});
console.log(result);
// ===>arr[6,10,100]

//箭头函数的方法\1-1
const arr = [1,6,9,10,100,25];
const result = arr.filter((item) => {
    if(item % 2 ===0){
        return true; 
    }else{
        return false;
    }
});
console.log(result);
// ===>arr[6,10,100]

//箭头函数的方法\1-2--省略小括号
const arr = [1,6,9,10,100,25];
const result = arr.filter(item => {
    if(item % 2 ===0){
        return true; 
    }else{
        return false;
    }
});
console.log(result);
// ===>arr[6,10,100]

//箭头函数的方法\1-3 超级简化
const arr = [1,6,9,10,100,25];
const result = arr.filter(item => item % 2 ===0);
console.log(result);
// ===>arr[6,10,100]

说明filter函数

参数

item: 会将遍历数组中的每一个元素当作实参传递给 item

return

true: 条件判断为真时,直接返回当前遍历的数组的元素 即 item 的值,并添加到新的数组里面。

fales:条件判断为假时,不返回任何值,继续遍历数组。


**箭头函数合适与 this 无关的回调 **

  1. 定时器
  2. 数组的方法回调

箭头函数不适合与 this 有关的事件回调函数

  1. DOM元素的事件回调函数,因为此时的 this 时指向事件源的;

  2. 对象的方法;

    {
    //对象的方法
    name : ‘菜鸟’;
    getName : function(){
    this.name; //此时的 this 指向的是 对象的 name
    }

     //使用箭头函数
     getName :() => {
         this.name;  //此时的 this 指向对象作用域以外的作用域
     }
    

    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值