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.
As requested (and because this is going to be open source later), here's the whole class and the thing that calls it:
class gameController extends instance {
constructor(name="untitled") {
super(name);
this.camera = null;
this.rendering = {"FPS":0,"cnv":null,"ctx":null}
this.sprites = [];
this.data.renderFrame = 0;
}
render() {
drawRect(0,0,canvas.width,canvas.height,3);
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) {
return setInterval(this.render,1000/fps);
}
}
const game = new gameController("game");
game.setRenderInterval(30); // called from script/devconsole