为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

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 关注
  • 73 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信