如何自动调用类内部的函数

我正在为我的游戏编写一个跟踪统计数据的机器人。我正在为每个独特的玩家创建一个类来跟踪他们的个人统计数据。默认情况下,类中的统计数据设置为 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 goals


console.log(newProfile.goalsDifference) // Get the updated goal difference


// Expected output: 5

// Actual output: 0

谢谢!


qq_花开花谢_0
浏览 77回答 1
1回答

倚天杖

你想在这里使用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 中的函数。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript