Michael Guimaraes
Michael Guimaraes

Reputation: 373

Uncaught TypeError: Cannot set property '0' of undefined

I am trying to insert a value into an array but when i try to insert the value it gives me the Connot set Property '0' of undefined. But clearly i defined the array already.

Error Line:

this.enemyMinions[i] = new EnemyCombatMinion(new Minion(enemyMinionInfo[0], 0, enemyMinionInfo[1], enemyMinionInfo[2], enemyMinionInfo[3], 0, 0, 0, 0, 0, 0));

And this is the entire code:

function Combat() {
  this.enemyMinions = [];
  this.playerMinions = [];
  this.currentEnemyMinion = null;
  this.currentPlayerMinion = null;
}

Combat.prototype.initialize = function() {
  var o = 0;
  for(var i = 0; i < partySlots.length; i++) {
    if(partySlots[i]) {
      this.playerMinions[o] = PlayerCombatMinion(partySlots[i]);
      o++;
    }
  }
  this.currentPlayerMinion = this.playerMinions[0];

   $.ajax({
      url: "./api/generateEnemyCombatMinions.php",
      cache: false
    })
    .done(function( html ) {          
      var response = html.split(":::");
      for(var i = 0; i < response.length; i++) {
        var enemyMinionInfo = response[i].split("::");
        this.enemyMinions[i] = new EnemyCombatMinion(new Minion(enemyMinionInfo[0], 0, enemyMinionInfo[1], enemyMinionInfo[2], enemyMinionInfo[3], 0, 0, 0, 0, 0, 0));
      }
      alert(this.enemyMinions.length);
    });   

}

As you see, i declared this.enemyMinons as a literal in the class constructor, and try to define a value to it in the initialize method.

Upvotes: 1

Views: 1496

Answers (1)

Sirko
Sirko

Reputation: 74106

The done() callback does not use your Combat object as this. Save a pointer to the object in the initialize() function, so that you can access the object later on.

Combat.prototype.initialize = function() {
  var o = 0;
  for(var i = 0; i < partySlots.length; i++) {
    if(partySlots[i]) {
      this.playerMinions[o] = PlayerCombatMinion(partySlots[i]);
      o++;
    }
  }
  this.currentPlayerMinion = this.playerMinions[0];

  // this is new
  var that= this;

   $.ajax({
      url: "./api/generateEnemyCombatMinions.php",
      cache: false
    })
    .done(function( html ) {          
      var response = html.split(":::");
      for(var i = 0; i < response.length; i++) {
        var enemyMinionInfo = response[i].split("::");
        // use "that" here instead of "this"
        that.enemyMinions[i] = new EnemyCombatMinion(new Minion(enemyMinionInfo[0], 0, enemyMinionInfo[1], enemyMinionInfo[2], enemyMinionInfo[3], 0, 0, 0, 0, 0, 0));
      }
      alert(that.enemyMinions.length);
    });   

}

Upvotes: 5

Related Questions