JS回调函数中this指向问题

45 阅读1分钟

回调函数中this的指向问题主要分为两种情况

1. 普通函数

当回调函数是普通函数时,回调函数中的this指向window(非严格模式下指向undefined),因为回调函数是被直接调用,并没通过.链式调用。

var name = 'window'

const obj1 = {
  name: 'test1',
  test: function(callback) {
    callback()
  }
}
const obj2 = {
  name: 'test2',
  foo:  obj1.test(function() {
      console.log(this.name)
    })
}

obj2.foo // window

可以通过call、apply、bind指定回调函数中this的指向

var name = 'window'

const obj1 = {
  name: 'test1',
  test: function(callback) {
    callback.apply(obj1)
  }
}
const obj2 = {
  name: 'test2',
  foo:  obj1.test(function() {
      console.log(this.name)
    })
}

obj2.foo // test1

2. 箭头函数

当回调函数是箭头函数时,回调函数中的this指向其上下文中的this

var name = 'window'

const obj1 = {
  name: 'test1',
  test: function(callback) {
    callback.apply(obj1)
  }
}
const obj2 = {
  name: 'test2',
  foo:  obj1.test(() => {
      console.log(this.name)
    })
}

obj2.foo // 其上下文this指向全局对象 window 
var name = 'window'

const obj1 = {
  name: 'test1',
  test: function(callback) {
    callback.apply(obj1)
  }
}
const obj2 = {
  name: 'test2',
  foo: function() {
    obj1.test(() => {
      console.log(this.name)
    })
  } 
}

obj2.foo() // 其上下文this指向调用对象obj2 window test2