ES2015 箭头函数( Arrow functions ) 与 this

本文探讨了ES2015中箭头函数的特点,重点在于其不绑定this值的特性,从而解决了在回调函数中处理this指针的问题。通过实例展示了如何在不需要额外保存this的情况下,利用箭头函数简化代码。
摘要由CSDN通过智能技术生成

箭头函数没有this的机制,箭头函数不会改变this的指向

第一个例子

const person = {
  name:'tom',
  sayHi:function(){
    console.log(`hi,my name is ${this.name}`)
  }
}
person.sayHi()// hi,my name is tom



const person = {
  name:'tom',
  sayHi:()=>{
    console.log(`hi,my name is ${this.name}`)
  }
}
person.sayHi()// hi,my name is undefined

第二个例子

const person = {
  name:'tom',
  sayHiAsync:function(){
    setTimeout(function(){
      // 这个回调函数最终会被放在全局对象上调用,所以拿不到this.name。输出undefined
       console.log(this.name)
    },1000)
  }
}
person.sayHiAsync()// undefined

那如果想在setTimeout回调函数里拿到this.name,怎么做呢?

以前的解决方案:把当前this存下来,借助闭包

const person = {
  name:'tom',
  sayHiAsync:function(){
    // 借助闭包
    const _this = this;
    setTimeout(function(){
       console.log(_this.name)
    },1000)
  }
}
person.sayHiAsync()// tom

有了箭头函数之后,我们就不用这么麻烦了:

// 现在的做法。箭头函数
const person = {
  name:'tom',
  sayHiAsync:function(){
    // 箭头函数的this始终指向当前作用域的this
    setTimeout(()=>{
       console.log(this.name)
    },1000)
  }
}
person.sayHiAsync()// tom

总结一下:

但凡需要使用_this 这种情况,我们都可以使用箭头函数去避免

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值