箭头函数和bind对this的作用

本文深入探讨JavaScript中箭头函数与bind()方法如何影响this的指向。通过实例解析,揭示它们在不同场景下的应用和区别,帮助开发者更好地理解this的关键概念。
var obj = {
  id: '哈哈哈',
  cool: function fn() {
    console.log('cool:')
    console.log(this)
    var self = this // 不起作用呀感觉
    if (self !== 1) {
      console.log('coolSelf:')
      console.log(self)
    }
  },
  coolTwo: () => {
    console.log('coolTwo:')
    console.log(this)
  },
  coolThree: () => {
    console.log('coolThree:')
    console.log(this)
  },
  coolFour: function coolFn() {
    console.log('coolFour:')
    console.log(this)
    setTimeout( function () {
      console.log('coolFour:无bind')
      console.log(this)
    }, 100)
    setTimeout( function () {
      console.log('coolFour:有bind')
      console.log(this)
    }.bind(this), 100) // bind this到coolFour环境
  },
  coolFive: () => { // 只要是箭头函数,你得bind this也会不起作用,还是会动态绑定到执行环境
    console.log('coolFive:')
    console.log(this)
    setTimeout( function () {
      console.log('coolFive:无bind 箭头函数下')
      console.log(this)
    }, 100)
    setTimeout( function () {
      console.log('coolFive:有bind 箭头函数下')
      console.log(this)
    }.bind(this), 100)
  }
}
var id = '呵呵呵'

obj.cool() // this是obj对象
obj.coolTwo() // this是window,由于=>函数’继承‘了obj.coolTwo函数运行时得this环境绑定 || =>函数之后可以抹杀词法作用域,而实现this动态作用域
obj.coolThree()
obj.coolFour()
obj.coolFive()
setTimeout( obj.cool, 100) // 另一个线程,this是window   测试var self = this也不起作用,不能够绑定this
setTimeout( obj.coolTwo, 100) // 另一个线程,即使没有跳到另一个线程,因为=>函数得存在,this也会指向window
setTimeout( obj.coolThree.bind(this), 100) // bind this到window

效果如下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值