1

I have made the following object in javascript :

var gr = {
    SIZE : 30,
    NO_X : (window.innerWidth / this.SIZE),
    NO_Y : (window.innerHeight / this.SIZE),
    drawGrid : function(){
        console.log(`NO_X : ${this.NO_X}`);
        console.log(`NO_Y : ${this.NO_Y}`);

        //
        //grid drawing function here
        //
    }
}

when I call the drawGrid function, the console log statements return the values of both NO_X and NO_Y as NaN, I would like them to equal the screen width / SIZE .

If I use window.innerWidth outside of the object it works as expected.

Sorry if the answer is obvious I am pretty new to programming in javascript.

thanks!

Daniel Davies
  • 118
  • 10

1 Answers1

1

You can convert NO_X and NO_Y to getters instead like:

get NO_X() {
    return window.innerWidth / this.SIZE
  },
  get NO_Y() {
    return window.innerHeight / this.SIZE
  },  

and then you should be able to access this.NO_X and this.NO_Y inside drawGrid properly. In this way you can draw grid with any size you want, instead of a fixed size 30.

var gr = {
  SIZE: 30,
  get NO_X() {
    return window.innerWidth / this.SIZE
  },
  get NO_Y() {
    return window.innerHeight / this.SIZE
  },
  drawGrid: function() {
    console.log(`NO_X : ${this.NO_X}`);
    console.log(`NO_Y : ${this.NO_Y}`);
  }
}

// Draw grid with size 30
gr.drawGrid()


// Draw grid with size 20
gr.SIZE = 20
gr.drawGrid()
palaѕн
  • 72,112
  • 17
  • 116
  • 136