[英]How to assign a Javascript variable to the same value of another variable
[英]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.