qq_花開花謝_0
2023-08-18 17:24:30
我正在為我的游戲編寫一個跟蹤統(tǒng)計數(shù)據(jù)的機器人。我正在為每個獨特的玩家創(chuàng)建一個類來跟蹤他們的個人統(tǒng)計數(shù)據(jù)。默認情況下,類中的統(tǒng)計數(shù)據(jù)設置為 0,我在游戲過程中操縱它們。我在嘗試在課堂上進行高級統(tǒng)計計算時遇到了困難。請預覽下面的代碼以了解。班上class Profile { constructor(username, nickname, auth) { this.username = username; // The player's registered name ... this.goalsAllowed = 0; this.goalsFor = 0; this.goalsDifference = function plusMinus() { // Find the difference between GoalsFor and GoalsAllowed return this.goalsFor - this.goalsAllowed; } }}創(chuàng)建類const newProfile = new Profile(playerName, playerName, playerAuth,)這會導致錯誤。我嘗試過使用方法,嘗試過不使用函數(shù)this.goalsDifference = this.goalsFor = this.goalsAllowed;但這似乎只在創(chuàng)建類時運行,并且我需要它在每次對 goalFor 或 goalAllowed 屬性進行更改時運行。我該如何處理這個問題?我在下面發(fā)布了一些關(guān)于我打算實現(xiàn)的目標class Profile { constructor(username) { this.username = username; // The player's registered name this.goalsAllowed = 0; this.goalsFor = 0; this.goalsDifference = this.goalsFor - this.goalsAllowed; }}const newProfile = new Profile("John");newProfile.goalsFor = 5; // Make a change to this profile's goalsconsole.log(newProfile.goalsDifference) // Get the updated goal difference// Expected output: 5// Actual output: 0謝謝!
1 回答

倚天杖
TA貢獻1828條經(jīng)驗 獲得超3個贊
你想在這里使用getter:
class Profile {
? ?constructor(username) {
? ? this.username = username; // The player's registered name
? ? this.goalsAllowed = 0;
? ? this.goalsFor = 0;
? }
? get goalsDifference() {
? ? return this.goalsFor - this.goalsAllowed;
? }
}
const newProfile = new Profile("John");
newProfile.goalsFor = 5;
console.log(newProfile.goalsDifference)
newProfile.goalsAllowed = 1;
console.log(newProfile.goalsDifference)
每次goalsDifference
使用時都會重新運行 getter 中的函數(shù)。
添加回答
舉報
0/150
提交
取消