James
James

Reputation: 461

Newly Created Objects from Class Return Undefined

I've created a Player class with some methods in it. I can create a player successfully, but when I go to call another method on the newly created player, I get undefined.

While the Player class will ultimately be used in another class class Scoreboard extends Player, I can't see why I can't invoke functions on a Player object.

Here's my Player class:

class Player {

  constructor(player_id, score) {
   this.player_id = player_id;
   this.scores = [score];
   this.total = score;
    }

  addScore(score) {
    this.total += score;
    this.scores.push(score);
  }

  averageScore() {
    return this.scores.length ? this.total / this.scores.length : 0;
  }

  resetScore() {
    this.scores = [];
    this.score = 0;
    }

  };

I create a new Player with the following: const john = new Player(2, 50); and call john, which in my console returns:

Player {player_id: 2, scores: Array(1), total: 50}
player_id: 2
scores: (2) [50, 70]
total: 120
__proto__: Object

Immediately after that, I call john.addScore(70) and get undefined. I would have thought that using this would prevent any undefined errors. What's wrong with my class?

Upvotes: 0

Views: 77

Answers (1)

Szellem
Szellem

Reputation: 514

addScore() returns undefined, that's what you see on the console. It's not an error.

Upvotes: 2

Related Questions