鼠标事件侦听器中的超时功能但更新全局变量

Timeout function in mouse event listener but updating global variable

我正在创建一个函数,该函数在单击鼠标时激活,但在 10 秒内无法通过使用 setTimeout() 再次触发。超时后,我的变量未设置为所需的布尔值。

//Called on every mouseclick
@HostListener("document:click", ["$event"])
public documentClick() {
console.log("1: " + this.active);

  //Only enter if true
  if (this.active === true) {

    //Setting active = false so user cannot enter here again
    this.active = false;
    console.log("2: " + this.active); 

    //10 seconds delay before active = true again
    setTimeout(function() {
      this.active = true;
      console.log("3: " + this.active);
      //Prints as true after 10 seconds
    }, 10000);

  }

}

一旦超时结束 this.active 设置为 true 但当我在超时后再次单击时,“1: false” 打印到控制台时应该为 true?

this 关键字在 Javascript 函数中指的是函数的作用域。要使用成员变量,请使用箭头函数。尝试以下

setTimeout(() => {  // <-- use arrow function here
  this.active = true;
  console.log("3: " + this.active);
  //Prints as true after 10 seconds
}, 10000);