98-js-14-this指向

概述

this 的取值是在执行时确定的,不是定义时候确定的

this的应用场景

作为普通函数

function fn1() {
  console.log(this)
}
fn1() // window

使用 call apply bind

function fn1() {
  console.log(this)
}
fn1.call({ X:100 })  // {X: 100}

const fn2 = fn1.bind({ x:200 })
fn2()  // {x: 200}

作为对象方法被调用

const zhangsan = {
  name: 'zhangsan',
  sayHi() {
    // this 即当前对象
    console.log(this)
  },
  wait() {
    setTimeout(function() {
      // this === window
      console.log(this)
    })
  }
}
zhangsan.sayHi() // {name: "zhangsan", sayHi: ƒ, wait: ƒ}
zhangsan.wait() // window

箭头函数

const zhangsan = {
  name: 'zhangsan',
  sayHi() {
    // this 即当前对象
    console.log(this)
  },
  wait() {
    setTimeout(() => {
      // this 即当前对象
      console.log(this)
    })
  }
}
zhangsan.sayHi() // {name: "zhangsan", sayHi: ƒ, wait: ƒ}
zhangsan.wait() // {name: "zhangsan", sayHi: ƒ, wait: ƒ}

在 class 方法中调用

class People {
  constructor(name) {
    this.name = name
  }
  sayHi() {
    console.log(this)
  }
}
const zhangsan = new People('zhangsan')
zhangsan.sayHi() // zhangsan对象: People {name: "zhangsan"}