this指向

70 阅读1分钟

普通函数

普通函数的调用方式决定了this指向谁

// 普通函数:  谁调用我,this就指向谁
console.log(this)  // window
function fn() {
  console.log(this)  // window    
}
// window.fn()
fn()

// window.setTimeout(function () {
setTimeout(function () {
  console.log(this) // window 
}, 1000)

document.querySelector('button').addEventListener('click', function () {
  console.log(this)  // 指向 button
})

const obj = {
  sayHi: function () {
    console.log(this)  // 指向 obj
  }
}
obj.sayHi()

严格模式下没有œ调用者时 this 的值为 undefined

image.png

箭头函数

上箭头函数中并不存在 this

  1. 箭头函数会默认帮我们绑定外层 this 的值,所以在箭头函数中 this 的值和外层的 this 是一样的

2.箭头函数中的this引用的就是最近作用域中的this

3.向外层作用域中,一层一层查找this,直到有this的定义

注意情况1:

在开发中【使用箭头函数前需要考虑函数中 this 的值】,事件回调函数使用箭头函数时,this 为全局的 window

因此DOM事件回调函数如果里面需要DOM对象的this,则不推荐使用箭头函数

image.png

注意情况2:

同样由于箭头函数 this 的原因,基于原型的面向对象也不推荐采用箭头函数

image.png

总结:

  1. 函数内不存在this,沿用上一级的

  2. 不适用

    构造函数,原型函数,dom事件函数等等

  3. 适用

    需要使用上层this的地方