[英]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.