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

效果如下

箭头函数和bind对this的作用

相关文章:

  • 2019-11-15
  • 2019-06-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案