0

So I'm writing a game on JS Canvas and I'm making my own GUI from scratch. To do so, I made a button object with fields x, y, width, height and intersects(click_event). For some reason, when I directly put this expression for x, it returns NaN even though the expression works everywhere else.

It's just a simple game on Canvas. I know I could probably use some dirty trick to work around it, but I want to keep my code clean. I just don't understand why this wouldn't work.

var button = {
    height:80, 
    width:200, 
    x:canvas.width/2 - this.width/2, //this is the problem
    y:200, 
    //other stuff
};



console.log(button.x);  //this prints "NaN"
console.log(canvas.width/2 - button.width/2);  //prints correct num

The canvas width is 1000, so 1000 / 2 - 200 / 2 should equal 400, which it does when called inside console.log.

But when I put it inside button.x it evaluates to NaN.

unhappycat
  • 406
  • 1
  • 4
  • 16
  • `this.width` must be an issue. While constructing the object, you are accessing another property, that doesn't look right – PM. Jan 21 '19 at 03:08
  • 3
    `this.` is not the `this` you think this is – Jaromanda X Jan 21 '19 at 03:09
  • You need to write a get method to do the calucation for you, have a look at the answer of https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers – PM. Jan 21 '19 at 03:10

2 Answers2

1

You can't access/reference a property within a object during initialization.

So this will never work:

var myObject = {
  height: 2
  doubleHeight: 2 * this.height 
}

One solution would be to add the poperty after you have initialized the object. Your code would like this:

var button = {
    height:80, 
    width:200, 
    y:200, 
    //other stuff
};
button.x = canvas.width/2 - button.width/2

Another solution would be to wrap inside function

function createButton(height, width, canvasWidth) {
  return {
    height: height,
    width: width,
    y: width,
    x: canvasWidth/2 - width/2
  }
}
Bergur
  • 3,962
  • 12
  • 20
0

It can be achieved by using constructor function

var button = new function() {
    this.height=80; 
    this.width=200;
    this.x = canvas.width/2 - this.width/2;
    this.y=200; 
}
Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47