0

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!

asked Nov 19, 2020 at 14:40
0

1 Answer 1

2

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.

answered Nov 19, 2020 at 14:47
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.