对象内部的变量不会公开更改

Variable inside object wont change publicly

这可能是一个非常愚蠢的问题,我对 javascript 几乎一无所知。当我在 class 函数之一内更改对象的变量时,它不会更改。 “我真的无法很好地解释事情。”在这种情况下,当我尝试“关闭”此 class 时,this.Status 仅在 Stop 函数的范围内 = Off。

注意:我正在使用 Node.js

代码

module.exports = class Sniper {

    constructor() {
        this.Status = 'Off'
    }

    async start() {
        this.Status = 'On'

        while (this.Status == 'On') {
            console.log(this.Status)
        }

    }

    stop() {
        //When I try to change this value, it only changes in this scope, so the while loop in the start function keeps running
        this.Status = 'Off'
        console.log(this.Status)
    }

}

我该如何解决这个问题?

您创建了一个无限循环。如果你将一个函数标记为 async 它仍然是同步的,但你可以在其中启动并等待 Promises

这个逻辑行不通,不确定你到底想要什么,但你不能从其范围之外停止同步无限 while 循环。

我能想象的最接近的是这样的:

 class Sniper {

    constructor() {
        this.Status = 'Off'
    }

    async start() {
        this.Status = 'On'

        while (this.Status === 'On') {
// Lets just give a bit of time for the engine to run other code
            await new Promise(resolve=>setTimeout(resolve,10));
            console.log(this.Status)
        }

    }

    stop() {
        //When I try to change this value, it only changes in this scope, so the while loop in the start function keeps running
        this.Status = 'Off'
        console.log(this.Status)
    }

}

const sniper = new Sniper();

sniper.start();

setTimeout(()=>{
 sniper.stop();
},1000);

这将启动您的循环,您可以随时停止它。但是正如我所说,我不确定你想达到什么目的

如果我能理解的话,你在这里找setInterval。您可以使用 intervalId 启动和停止它。比使用 while 循环和阻塞唯一的执行线程更好。

class Sniper {
  constructor() {
    this.Status = "Off";
    this.intervalId = null;
  }

  start() {
    this.Status = "On";

    this.intervalId = setInterval(() => {
      console.log(this.Status);
    }, 1000);
  }

  stop() {
    console.log("Turning off!");
    this.Status = "Off";
    clearInterval(this.intervalId);
  }
}

const foo = new Sniper();
foo.start();

setTimeout(() => {
  foo.stop();
}, 5000);

这将输出:

On
On
On
On
Turning off!