JavaScript作用域和setTimeout位于;“类”;

JavaScript作用域和setTimeout位于;“类”;,javascript,scope,settimeout,Javascript,Scope,Settimeout,我很难解决范围问题。实际上我正在为HMI浏览器前端做一个项目。它应该可视化自动化系统中的变量。对于HMI,要求用户可以在不同页面之间切换。为了解决一般的流程,我创建了一个状态机函数,它协调加载、绘制和与用户的交互。我现在的问题是,我使用setTimeout调用run函数(实际上是我的状态机),现在使用var scope运行时遇到了问题 请看以下代码: function frontend() { // Public properties: this.soundEnable = true;

我很难解决范围问题。实际上我正在为HMI浏览器前端做一个项目。它应该可视化自动化系统中的变量。对于HMI,要求用户可以在不同页面之间切换。为了解决一般的流程,我创建了一个状态机函数,它协调加载、绘制和与用户的交互。我现在的问题是,我使用setTimeout调用run函数(实际上是我的状态机),现在使用var scope运行时遇到了问题

请看以下代码:

function frontend() {

  // Public properties:
  this.soundEnable = true;

  // Private Properties:
  var p1 = 0;
  var p2 = [1,2,3];
  var p3 = {a:1, b:2, c:3};
  var runState = 1;
  var runWait = false:

  // Public Methods

  // stops the state machine until m_continue is called
  this.m_wait = function() {
    runWait = true;
  }

  // continues the state machine
  this.m_continue = function() {
    if (runWait) {
      runWait = false;
      setTimeout(run, 100);
    }
  }

  // Private Methods

  function drawFrame(finish_callback) {
    ...<Drawing of HMI-Objects on the canvas>...
    finish_callback();
  }

  function run() {
    switch (runState) {
    case 1:
      this.m_stop();
      drawFrame(this.m_continue());
    case 2:
      for(i=0; i<p3.length; i++) {
        p2.push(externalObjectCreator(p3[i]));
      }
    }
    if (!runWait) {
      runState++;
      setTimeout(run, 100);
    }
  }

  // Constructor
  ...<code to assign public and private properties>...

  // Finally call the state machine to activate the frontend
  runState = 1;
  run();
}
函数前端(){
//公共财产:
this.soundEnable=true;
//私人物业:
var p1=0;
var p2=[1,2,3];
var p3={a:1,b:2,c:3};
var-runState=1;
var runWait=false:
//公共方法
//停止状态机,直到调用m_continue
this.m_wait=函数(){
runWait=true;
}
//继续使用状态机
this.m_continue=函数(){
如果(运行等待){
runWait=false;
设置超时(运行,100);
}
}
//私有方法
函数drawFrame(finish\u回调){
......
finish_callback();
}
函数运行(){
开关(运行状态){
案例1:
这个。m_stop();
drawFrame(this.m_continue());
案例2:

对于(i=0;i来说,最简单的方法是像这样定义您的作用域

this.m_continue = function() {
 that = this;  
 if (runWait) {
      runWait = false;
      setTimeout(that.run, 100);
    }
  }

否则,您也可以使用
apply

使用范围绑定。您应该在每个setTimeout中绑定run函数,因为run使用

setTimeout(run.bind(this), 100);