跳到主要内容

this 有几种赋值情况,如何取值?

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

this 有几种赋值情况

  • 作为普通函数
  • 使用 call apply bind
function fn1() {
console.log(this)
}
fn1() // window
fn1.call({x: 100}) // {x: 100}
fn1.apply({x: 200}) // {x: 200}
const fn2 = fn1.bind({x: 300})
fn2() // {x: 300}
  • 作为对象方法被调用
const zhangsan = {
name: '张三',
sayHi() {
// this 即当前对象
console.log(this)
},
wait() {
setTimeout(function () {
// this === window
console.log(this)
})
},
waitAgain() {
setTimeout(() => {
// this 即当前对象
console.log(this)
})
}
}
zhangsan.sayHi()
zhangsan.wait()
zhangsan.waitAgain()
  • 在 class 方法中调用
class People {
constructor(name) {
this.name = name
}
sayHi() {
console.log(this)
}
}
const lisi = new People('李四')
lisi.sayHi() // lisi 对象
  • 箭头函数