JS中的this指向问题

class Button {
  constructor() {
    this.click = function() {
      console.log(this)
    }
  }
}

let button = new Button()
let test = button.click
test()    //  输出undefined, 为什么不是window?

因为在严格模式下,函数内部的this默认为undefined,而不是全局对象window。在上述代码中,test()函数的执行环境是全局环境,因此this指向undefined。如果想让this指向全局对象window,可以使用箭头函数,或者显式地绑定this。例如:

使用箭头函数:


class Button {
  constructor() {
    this.click = () => {
      console.log(this)
    }
  }
}
 
let button = new Button()
let test = button.click
test()    // 输出window对象

由于 this.click 中使用了函数表达式来定义 click 方法,它的 this 指向的是 Button 实例本身,而不是全局对象。因此,在调用 test() 时,this 指向 undefined。