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

Javascript 为什么这个表达式等于NaN,但在其他地方定义时等于有效答案?,javascript,object,field,Javascript,Object,Field,所以我在JS画布上写了一个游戏,我从头开始制作自己的GUI。为此,我制作了一个按钮对象,其中包含x、y、宽度、高度和相交字段(单击事件)。出于某种原因,当我直接将此表达式放在x中时,它返回NaN,即使该表达式在其他任何地方都适用 这只是画布上的一个简单游戏。我知道我可能会使用一些肮脏的伎俩来解决它,但我想保持我的代码干净。我只是不明白为什么这样不行 var button = { height:80, width:200, x:canvas.width/2 - this

所以我在JS画布上写了一个游戏,我从头开始制作自己的GUI。为此,我制作了一个
按钮
对象,其中包含
x、y、宽度、高度
相交字段(单击事件)
。出于某种原因,当我直接将此表达式放在
x
中时,它返回
NaN
,即使该表达式在其他任何地方都适用

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

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 
}
一种解决方案是在初始化对象后添加poperty。您的代码如下所示:

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

此.width
一定是个问题。在构造对象时,您正在访问另一个属性,它看起来不正确
this.
不是
this
您认为这是您需要编写一个get方法来为您执行计算,请查看