为什么此表达式等于 NaN,但在其他地方定义时等于有效答案?

Why does this expression equal NaN, but equal a valid answer when defined somewhere else?

所以我正在用 JS Canvas 编写游戏,并且我正在从头开始制作自己的 GUI。为此,我创建了一个包含字段 x, y, width, heightintersects(click_event)button 对象。出于某种原因,当我直接将此表达式用于 x 时,它 returns NaN 即使该表达式在其他任何地方都有效。

这只是 Canvas 上的一个简单游戏。我知道我可能会使用一些肮脏的技巧来解决它,但我想保持我的代码干净。我只是不明白为什么这行不通。

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

canvas 宽度为 1000,因此 1000 / 2 - 200 / 2 应等于 400,在 console.log.

内部调用时它会这样做

但是当我把它放在 button.x 里面时,它的计算结果是 NaN

您不能在初始化期间在对象中 access/reference 一个 属性。

所以这永远行不通:

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

一种解决方案是在初始化对象后添加属性。您的代码如下:

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

另一种解决方案是将函数包装在内部

function createButton(height, width, canvasWidth) {
  return {
    height: height,
    width: width,
    y: width,
    x: canvasWidth/2 - width/2
  }
}

可以使用构造函数实现

var button = new function() {
    this.height=80; 
    this.width=200;
    this.x = canvas.width/2 - this.width/2;
    this.y=200; 
}