render() {
drawRect(0,0,canvas.width,canvas.height,3);
console.log(this) // when called with setInterval(classObject.render, 1000), returns window; if called with (classObject).render returns (classObject)
for (let i = 0; i <= this.sprites.length; i++) {
if (this.sprites[i]) {
let cs = this.sprites[i]
cs.drawRoutine(cs.position.x,cs.position.y);
}
}
}
setRenderInterval(fps) {
setInterval(this.render,1000/fps);
}
Here, let’s assume classObject
is called game
.
When game.render()
is called normally, it has game
as this
. But when it’s called using setInterval, it has window
as this
. How can I circumvent this?
this.sprites
is an array of sprites for the game, and it needs to be accessed using this, as there can be multiple games with different variable names. And cs.drawRoutine is a function within the sprite that just draws in the canvas. The function runs when normally called.