繁体   English   中英

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

[英]JavaScript: How can I assign a variable the same as another variable inside the same object?

对不起,如果这是重复的,但我找不到其他人。

所以我尝试这样做。

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内部player1 ,它被“使用”。

顺便说一句,我这样做是因为对称。

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

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

考虑使用getter

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

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

 var player1 = { width: 20, height: 75, _x: null, _y: null, get x() { return this._x || this.width + 10 }, set x (newX) { this._x = newX }, get y() { return this._y || this.height + 10 }, set y (newY) { this._y = newY } }; console.log(player1.x, player1.y); player1.x = 500; player1.y = 200; console.log(player1.x, player1.y);

由于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,
});

您无法访问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 但对于这两个属性,我会坚持第一个解决方案,它更清晰、更简单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM