本文介绍了`this` 的属性在 setTimeout 中未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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();

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

For some reason, the JS transpiled version of my TypeScript class throws an error in the onLoop function. It reports TypeError: this.gates is undefined. However, if I access sim (a Simulator object) and manually access the gates property it's defined. I can run the onLoop code manually from the console.

推荐答案

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

When functions are passed by reference, they lose their reference to this. You're losing this reference when calling setTimeout.

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

Functions have a bind() method that basically return a new function with a corrected reference to this.

这样称呼它:

setTimeout(this.onLoop.bind(this), 1000)

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

Alternatively, you can also pass an in-line arrow function. Arrow functions don't lose their this context.

setTimeout(() => this.onLoop(), 1000)

这篇关于`this` 的属性在 setTimeout 中未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 06:05