Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

329
Visualizações
setInterval setting this to window instead of class (calling class function)
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
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda