我正在為我的游戲編寫一個跟蹤統計數據的機器人。我正在為每個獨特的玩家創建一個類來跟蹤他們的個人統計數據。默認情況下,類中的統計數據設置為 0,我在游戲過程中操縱它們。我在嘗試在課堂上進行高級統計計算時遇到了困難。請預覽下面的代碼以了解。班上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; } }}創建類const newProfile = new Profile(playerName, playerName, playerAuth,)這會導致錯誤。我嘗試過使用方法,嘗試過不使用函數this.goalsDifference = this.goalsFor = this.goalsAllowed;但這似乎只在創建類時運行,并且我需要它在每次對 goalFor 或 goalAllowed 屬性進行更改時運行。我該如何處理這個問題?我在下面發布了一些關于我打算實現的目標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謝謝!
如何自動調用類內部的函數
qq_花開花謝_0
2023-08-18 17:24:30