Estoy tratando de llamar a una parte del código en una clase una y otra vez a cada segundo,
update() { for (let entity of this.entities) { if (entity instanceof Alien) { entity.y += 1; renderAliens(entity, this.context); } } } este es el código que estoy tratando de llamar dentro de mi objeto Game usando setInterval(newGame.update(),1000) , sin embargo, cuando intento hacer esto, aparece un error diciendo que Uncaught TypeError: this.entities is undefined , entiendo que esto se debe a un problema de alcance con this y setinterval, pero no estoy seguro de cómo usar bind para resolver el problema
editar: aquí está toda la pieza de código relevante
class Game { constructor() { this.gameOver = false; this.entities = []; this.context = document.getElementById("canvas").getContext("2d"); } start() { this.entities.push(new Ship(0, 400)); this.entities.push(new Alien(1, 0)); this.entities.push(new Alien(20, 0)); this.entities.push(new Alien(40, 0)); } render() { for (let entity of this.entities) { if (entity instanceof Alien) { renderAliens(entity, this.context); } else if (entity instanceof Ship) { renderShip(entity, this.context); } } } update() { for (let entity of this.entities) { if (entity instanceof Alien) { entity.y += 20; renderAliens(entity, this.context); } } } endGame() {} } const newGame = new Game(); newGame.start(); newGame.render(); let t = setInterval(newGame.update, 1000);Tienes dos opciones:
.bind() . Esto this une a la instancia de newGame setInterval(newGame.update.bind(newGame), 1000); setInterval(function(){ newGame.update(); }, 1000);Solo escribe el intervalo como:
const intervalRef = setInterval(() => { newGame.update() }, 1000);¿Por qué no simplemente declaras el intervalo en tu constructor? De esta manera, evitará cualquier problema de contexto.
constructor() { this.gameOver = false; this.entities = []; this.context = document.getElementById("canvas").getContext("2d"); setInterval(this.update.bind(this), 1000); // Here }