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



所以我正在 JS Canvas 上编写一个游戏,我从头开始制作自己的 GUI。为此,我创建了一个带有字段 x, y, width, heightintersects(click_event)button 对象。出于某种原因,当我直接将此表达式放在x 时,即使该表达式在其他任何地方都有效,它也会返回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
画布宽度为 1000,因此 1000/2

- 200/2 应等于 400,在 console.log 内调用时会这样做。

但是当我把它放在里面时button.x它的评估结果是NaN.

初始化

期间无法访问/引用对象中的属性。

所以这永远不会奏效:

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; 
}

最新更新