Когда this.onLoop
вызывается в setTimeout
, контекст вызова внутри onLoop
равен окну , поскольку setTimeout
является функцией объекта window .Вы можете исправить это, используя функцию стрелки, которая вызывает onLoop
, а не передает onLoop
напрямую:
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));
this.gates.push({ render: () => console.log('rendered') });
}
run() {
setTimeout(() => this.onLoop(), 1000);
}
onLoop() {
for (let gate of this.gates) {
gate.render();
}
}
}
let sim = new Simulator();
sim.initialize();
sim.run();
Или связав контекст this
функции onLoop
с созданным объектом:
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));
this.gates.push({ render: () => console.log('rendered') });
}
run() {
setTimeout(this.onLoop.bind(this), 1000);
}
onLoop() {
for (let gate of this.gates) {
gate.render();
}
}
}
let sim = new Simulator();
sim.initialize();
sim.run();