亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何自動調用類內部的函數

如何自動調用類內部的函數

qq_花開花謝_0 2023-08-18 17:24:30
我正在為我的游戲編寫一個跟蹤統計數據的機器人。我正在為每個獨特的玩家創建一個類來跟蹤他們的個人統計數據。默認情況下,類中的統計數據設置為 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謝謝!
查看完整描述

1 回答

?
倚天杖

TA貢獻1828條經驗 獲得超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 中的函數。



查看完整回答
反對 回復 2023-08-18
  • 1 回答
  • 0 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號