ES6 箭头函数

箭头函数

    使用 => 的方式替代了function,使代码更加简短、清晰易读,尤其是极大的简化了回调函数的编写。

普通方式编写函数

function fn(a){
     console.log('function:')
     return a+1;
}
console.log(fn(1));

使用箭头函数 编写

//箭头函数 编写
const fun = (a) => {
    console.log('fun invoked 箭头函数')
   return a+2;
}
console.log(fun(8));

箭头函数还极大的简化了回调函数


const arr = [1,2,3,4,5,6,7,8];
const arr1 = arr.filter(function(a){
  return a % 2;//只会返回a%2值为1的值
})
console.log(arr1);//[1,3,5,7]
//使用箭头函数
const arr2 = arr.filter(a => a%2);
console.log(arr2);//[1,3,5,7]
箭头函数的this:箭头函数内部是没有this机制,箭头函数中的this,所代表的指向值,是通过向外层查找得来的
const person = {
      name : "li",
      age : 21,
      message : function(){
              console.log(this.name + "," +this.age);
        }
};
person.message();

给person对象中的message方法中添加一个延时器,使用箭头函数,会发现在这个message()中,this的指向是不同的,在function中,this指向的是person,所以当延时器里需要指向person的this时,我们就可以手动的将person的指向赋给一个变量,此变量的作用也就相当于this了。

//箭头函数
const person = {
  name : "zhang",
  age : 21,
  message : function(){
      const _this = this;//function这里this指向的是person
      setTimeout(() =>{
      //这样需要使用this特定的指向时,使用_this即可
          console.log(_this.name + "," + _this.age);
      },1000);
      
  }
};
person.message();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值