JavaScript:如何在同一对象中分配与另一个变量相同的变量?
很抱歉,如果这是重复的,但是我找不到其他的 所以我试着这么做JavaScript:如何在同一对象中分配与另一个变量相同的变量?,javascript,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,
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
是在player1
中分配的,它被“使用”了
顺便说一句,我这样做是因为对称
我可以让这些变量自己使用,但我正在尝试清理我的代码
那么,如何通过使用对象来解决这个问题呢?考虑使用
var player1={
宽度:20,
身高:75,
get x(){返回this.width+10},
get y(){返回this.height+10}
};
log(player1.x,player1.y)代码> 自从代码> Prave1,宽度< /代码>还没有被定义——因为你仍然在定义<代码> Prave1<代码>的中间——你可以先定义它和其他静态属性,然后在下一行中用.< /P>分配动态的属性。
您无法从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
。但就这两个属性而言,我坚持第一个解决方案,它更清晰、更简单。如果x和y发生变化,我认为这不是它们的目的。@JacqueGoupil你可能是对的。如果OP试图保留直接设置x
的功能,这可能会使这一点更加复杂。我将添加一段额外的代码来说明这一点。
Object.assign(player1, {
x: canvas.width/6 - player1.width/2,
y: canvas.height/2 - player1.height/2;
});