access functions of a variable in a constructor js

2

I want to access the variable ctx which is located in the constructor of my game and in the loop function which accesses it to clean the canvas I get the error "main.js: 191 Uncaught TypeError: Can not read property ' clearRect 'of undefined " code- >

class JuegoSnake {
   constructor() {
    this.comidas = [];
    this.canv = document.getElementById("canvas");
    this.puntuacion = 0;
    this.ctx = this.canv.getContext("2d");
    this.scl = 40;
    this.canv.width = window.innerWidth;
    this.canv.height = Math.floor(window.innerHeight * 1);
    this.serpiente = new snake();
    this.comidas.push(new comida(this.scl));

}


draw() {

    this.ctx.clearRect(0, 0, this.canv.width, this.canv.height);
    drawFondo(this.ctx);
       }
    
asked by parrado 10.09.2018 в 22:27
source

1 answer

1

When you run draw these out of the context of the constructor, that is, you are in another time and place where the this.ctx does not exist. To correct this you can add this to your class

class JuegoSnake {
   constructor() {
    this.comidas = [];
// ...
    this.comidas.push(new comida(this.scl));

    // le pasamos el contexto actual de la clase
    this.draw = this.draw.bind(this);
   }

   draw(){
      console.log(this.ctx) // ahora tendra lo que necesitas
   }
}

Adding the bind append the current context of the class and you can invoke it: D as you expected.

More information about the context of this in:

link

    
answered by 11.09.2018 / 02:24
source