how to execute functions in the constructor of a class js

0

I wanted to execute a function of the own class in the constructor of that class, in this case the purpose was that the class was going to be a game so in the constructor when calling it a function was executed to initiate that modifies what was . but when calling the variable in the constructor I get that it is not defined.

class JuegoSnake {
  constructor() {

    this.scl = 40;
    this.canv.width = window.innerWidth;
    this.canv.height = Math.floor(window.innerHeight * 1);
    iniciar();

  }


  iniciar() {

    console.log("lo que sea");
  }
}
    
asked by parrado 11.09.2018 в 23:55
source

3 answers

2

You must call with this.

class JuegoSnake {
  constructor() {

    this.iniciar();
    this.scl = 40;
//modificación respecto al código del OP para hacer que funcione el constructor
    this.canv = {
      width : window.innerWidth,
      height : Math.floor(window.innerHeight * 1)
    }
  }


  iniciar() {
    console.log("lo que sea");
  }
}
new JuegoSnake();
    
answered by 12.09.2018 в 00:58
0

You simply reference the method with this . It is the correct and elegant way to do it.

class Person{
  constructor(nombre, age){
    this.nombre = nombre;
    this.age = age;
    // Se llama al método con [ this ]
    this.mostrarDatos();
  }
  
  mostrarDatos(){
    console.log(this.nombre + ' Tiene ' + this.age + ' años.');
    document.write(this.nombre + ' Tiene ' + this.age + ' años.');
  }
}

var yo = new Person('Fulanito Perez', 20);
    
answered by 12.09.2018 в 15:09
0

You can do it like this:

class JuegoSnake {
constructor() {

    this.scl = 40;
    this.canv = {};
    this.canv.width = window.innerWidth;
    this.canv.height = Math.floor(window.innerHeight * 1);
        
    this.iniciar = function() {

        console.log("lo que sea");
    }
    this.iniciar();
}

}


var juego = new JuegoSnake();
    
answered by 11.09.2018 в 23:59