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执行会有不同,主要集中在这几个场景中
- 作为构造函数执行
- 作为对象属性执行
- 作为普通函数执行
- 用于call apply bind
前两种情况咱们之前都介绍过了,这里只是统一的提出来,汇总一下,不再详细讲了。这里主要说第三种:
function fn() {
console.log(this)
}
fn() // window
fn.call({a:100}) // {a:100} 和 call 同理的还有 apply bind