函数中this指向主要包括哪些情况

很多人都觉得this的值不好确认。

其实不难,请记住:this的值在执行的时候才能确认,定义的时候不能确认。

这是因为:this是执行上下文的一部分,而执行上下文需要在代码执行之前确定,而不是定义的时候。

我们来看一个例子:

var a = {
  name: 'A',
  fn: function() {
    console.log(this.name)
  }
}
a.fn()  // this === a
a.fn.call({name: 'B'}) // this === {name: 'B'}
var fn1 = a.fn
fn1() // this === window

this执行会有不同,主要集中在这几个场景中:

1.作为构造函数执行,构造函数中

2.作为对象属性执行,上述代码中a.fn()

3.作为普通函数执行,上述代码中fn1()

4.用于call、apply、bind,上述代码中a.fn.call({name: ‘B’})

加油