this 指针详解

79 阅读1分钟

this指针

this指向无非就这几种情况 image.png

箭头函数

  • 本身是没有this,但是它的this指向是包裹第一个的普通函数的this
function a() {
  return () => {
    return () => {
      console.log(this)   // this是函数a的this,但是函数a的this指向是window
    }
  }
}
console.log(a()()()) 

bind apply call

  • 通过方法改变this指向
  • 重点提下bind方法,他的this指向是第一次调用的this,举个栗子
let obj = {name:"dog"}
fn.bind(obj)()   //this指向了obj   

函数如何被调用 (分2种情况)

  • new方式,this会被固化到实例上去(感兴趣可以了解下new的原生实现方法)
  • 通过obj.fn()的调用,this就为obj
  • 普通函数执行,this就为window