-1

I am trying to add a function to the BattleState object.
I am using the prototype method as I don't want the function to be serialised, as described in Use of 'prototype' vs. 'this' in JavaScript?

This is roughly how I have my code set up, when I call the getPlayerStateFromBattleState function, I get an error saying "TypeError: Cannot find default value for object." I assume it is the function that I've added to the prototype that can't be found, but I may be wrong. Does anyone know what is causing this?

function BattleState() {
  this.player1 = new PlayerState();
  this.player1.id = 1;
  this.player2 = new PlayerState();
  this.player2.id = 2;
};


BattleState.prototype.getPlayerStateFromBattleState = function(thisPlayerId) {
  if (this.player1.id == thisPlayerId) {
    return this.player1;
  } else if (this.player2.id == thisPlayerId) {
    return this.player2;
  } else {
    // Error
  }
}


var battleState = new BattleState();

// This line resutls in "TypeError: Cannot find default value for object."
var playerState = battleState.getPlayerStateFromBattleState(1);
Community
  • 1
  • 1

1 Answers1

0

I tried to reproduce the problem:

// This line resutls in "TypeError: Cannot find default value for object."
console.log(battleState.getPlayerStateFromBattleState(2));

https://jsfiddle.net/kg85w55e/

The given code just worked. I think there is something in your PlayerState Class. Could you Adjust your question and include your PlayerState Class?

Max Sassen
  • 650
  • 5
  • 15