JS中的this

this 这个东西一直很酷扰我。昨天更是让我 debug 了一夜。。。

于是决心记录一下 this

原理

正规调用函数方法是用 call(), 其中第一个参数就是 this, 即调用函数的对象。

1
fn().call(undefined,args[,,,])

如果 this 是 undefined, 在 DOM 中非严格模式下,this 就指向了 window

call , apply , bind

call() 执行的时候将剩余参数一次传入;
apply() 则将剩余参数作为数组传入。
bind() 只有一个参数, 那就是 this。 除了绑定 this 别无他用。

特例

绑定点击时间中的 this,指的是被触发的元素本身。

1
2
3
4
5
6
7
window.addEventListener('scroll',  function(e) {
if (window.scrollY > 0) {
this.active() // this 是被监听 元素
} else {
this.deactive()
}
})

箭头函数

()=>{} 中不绑定 this 的, 换言之,箭头函数中没有 this,如果出现 this, 向上查找。内外 this 不变。

1
2
3
4
5
6
7
8
9
10
bindEvents: function () {
let view = this.view
window.addEventListener('scroll', (e)=> {
if (window.scrollY > 0) {
this.active()// 上面 view 的 this 是同一个
} else {
this.deactive()
}
})
},

Tip

使用 VS code 可以轻松搞定 this。 但是有的时候不是很准确,但是大致可以确定 this 的指向。