`this` 的属性在 setTimeout 中未定义

Bas*_*ast 0 javascript this

class Simulator {
  constructor() {
    this.gates = Array();
    this.gates.push(new AndGate(200, 200));
  }
  initialize() {
    let canvas = document.getElementById('board');
    canvas.width = 800;
    canvas.height = 500;
    canvas.setAttribute("style", "border: 1px solid black");
    this.gates.push(new AndGate(100, 100));
  }
  run() {
    setTimeout(this.onLoop, 1000);
  }
  onLoop() {
    for (let gate of this.gates) {
      gate.render();
    }
  }
}
let sim = new Simulator();
sim.initialize();
sim.run();
Run Code Online (Sandbox Code Playgroud)

出于某种原因,我的 TypeScript 类的 JS 转译版本在onLoop函数中引发错误。它报告TypeError: this.gates is undefined。但是,如果我访问sim(一个 Simulator 对象)并手动访问它定义的 gates 属性。我可以从控制台手动运行 onLoop 代码。

Eve*_*ert 5

当函数通过引用传递时,它们会丢失对 的引用this。调用setTimeout.

函数有一个bind()方法,它基本上返回一个新函数,并修正了对 的引用this

这样称呼它:

setTimeout(this.onLoop.bind(this), 1000)
Run Code Online (Sandbox Code Playgroud)

或者,您也可以传递内嵌箭头函数。箭头函数不会丢失它们的this上下文。

setTimeout(() => this.onLoop(), 1000)
Run Code Online (Sandbox Code Playgroud)