Atomixx
Atomixx

Reputation: 270

How to call functions inside a class automatically

I am writing a bot for my game that tracks statistics. I am creating a class for every unique player to track their individual statistics. On default the statistics in the class are set to 0 and I manipulate them over the course of the game. I've been having difficulty when attempting to perform calculations for advanced statistics in the class. Please preview the code below to understand.

The class

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;
  }
  }
}

Creating the class

const newProfile = new Profile(playerName, playerName, playerAuth,)

This results in an error. I've tried using methods, tried not using functions

this.goalsDifference = this.goalsFor = this.goalsAllowed;

But this seems to only run when the class is created, and I need it to run everytime a change is made to the goalsFor or goalsAllowed properties. How do I approach this? I've posted some below as to what I intend to achieve

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

Thanks!

Upvotes: 0

Views: 48

Answers (1)

Liam
Liam

Reputation: 29754

You want to use a getter here:

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)

Every time goalsDifference is used it will re-run the function in the getter.

Upvotes: 2

Related Questions