如何在此方法内访问“变量”?

时间:2018-10-20 10:14:39

标签: javascript scope setinterval

class A{
  constructor(callback){
    this.monitor = null;
    this.callback = callback;
    this.interval = 1000
  }


  start(){
    this.monitor = setInterval(this.callback, this.interval);
  }

  stop(){
    clearInterval(this.monitor);
    this.monitor = null;
  }
}

class B{

  constructor(){
    this.runner = null;
    this.variable = 0;
  }

  turnOn(){
    this.run.bind(this);
    this.runner = new A(this.run);
    this.runner.start();
  }

  run(){
    console.log('Running', this.variable)
  }

  turnOff(){
    this.runner.stop()
  }
}

let b = new B()
b.turnOn()

setTimeout(() => {
  b.turnOff()
}, 50000)

我已经使用bind关键字解决了JS这个问题,但它似乎仍然无法正常工作。 this.variable返回undefined,因为这是指向Timeout的一个实例,我该如何更改

0 个答案:

没有答案