JavaScript:如何在同一对象内为变量分配与另一个变量相同的变量?

时间:2018-11-13 22:00:16

标签: javascript

很抱歉,如果这是重复的,但我找不到其他人。

所以我尝试这样做。

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");    

var player1 = {
    width: 20,
    height: 75,
    x: canvas.width/6-player1.width/2,
    y: canvas.height/2-player1.height/2,
    speed: 5
};

function drawPlayer1() {
    ctx.beginPath();
    ctx.rect(player1.x, player1.y, player1.width, player1.height);
    ctx.fillStyle = "#b10000";
    ctx.fill();
    ctx.closePath();
}

drawPlayer1();

但是问题是我无法将x分配给player1.width,因为width是在player1内部分配的,而该位置被“使用”。

顺便说一句,我这样做是出于对称性。

我可以自己拥有这些变量,但我正在尝试清理代码。

那么,如何使用对象来解决这个问题?

3 个答案:

答案 0 :(得分:4)

考虑使用getters

uint32_t val1 = 0xabcdabcd;
uint8_t val2 = 1;
uint8_t val3 = 0;
uint16_t val4 = 0;
uint8_t final_val[8];
#define ADDR (&final_val[0])
//The output format is as follows: NNNNNNNNxyz
// NNNNNNNN: value1  in hex 
// x - val2, 
// y - val3, 
// z - val4  
int main() {

   uint64_t *ptr = (uint64_t *)ADDR ;
   *ptr = val1<<31|val2<<24|val3<<16|val4;
   printf("%p  0x%x \n", ptr, *ptr);
   return 0;

}

如果您希望能够直接设置值并覆盖公式,则也可以使用setters

var player1 = {
  width: 20,
  height: 75,
  get x() { return this.width + 10 },
  get y() { return this.height + 10 }
};

console.log(player1.x, player1.y);

答案 1 :(得分:0)

由于尚未定义player1.width(由于仍处于定义player1的中间状态),因此可以先定义它和其他静态属性,然后在其上分配动态属性。 Object.assign的下一行。

var player1 = {
    width: 20,
    height: 75,
    speed: 5
};
Object.assign(player1, {
    x: canvas.width/6-player1.width/2,
    y: canvas.height/2-player1.height/2,
});

答案 2 :(得分:0)

您无法从player1的定义中访问player1,因为它尚不存在。当解释器解析此代码时,它首先根据对象文字创建一个对象,然后将其存储在player1变量中。而且由于player1事先不存在,所以player1.width会导致错误。

// original code which doesn't work
var player1 = {
    width: 20,
    height: 75,
    x: canvas.width/6-player1.width/2,
    y: canvas.height/2-player1.height/2,
    speed: 5
};

一种简单的解决方法是在创建对象之后设置这些变量。

var player1 = { ... };

player1.x = canvas.width/6 - player1.width/2;
player1.y = canvas.height/2 - player1.height/2;

或者,您可以执行以下操作:

Object.assign(player1, {
    x: canvas.width/6 - player1.width/2,
    y: canvas.height/2 - player1.height/2;
});

此代码使用x和y属性创建一个新对象,然后将它们复制到player1。但是对于这两个属性,我将坚持第一个解决方案,它更清晰,更简单。