Rodmentou
Rodmentou

Reputation: 1640

Why a reference to a reference don't update the original object?

Well, I'm making a function to update player's hp over time.

On my NodeJS side, I'm passing the players array to require('./addHp')(players); Inside addHp.js I have this fully working function:

module.exports = function (players) {

  var addHp = setInterval ( function () {
    for (var player in players) {
      var thisPlayer = players[player];
      (thisPlayer.hp < thisPlayer.maxHp) ? //Uggly
         thisPlayer.hp += 10 :             //Uggly
         thisPlayer.hp = thisPlayer.maxHp; //Uggly
    }
  }, 2000);

}

But it's really not too easy to read so I've made some changes:

module.exports = function (players) {
  var addHp = setInterval ( function () {

    for (var player in players) {
      var thisPlayer = players[player];
      var hp = thisPlayer.hp;
      var maxHp = thisPlayer.maxHp;

      (hp < maxHp) ? hp += 10 : hp = maxHp; //Beautiful

    }
  }, 2000);
}

All the proper values are reaching both hp and maxHp, but when I change the hp to 5000, the value of players[player].hp won't change. Why? And how can I use it this way?

Upvotes: 0

Views: 42

Answers (1)

Amit
Amit

Reputation: 46323

This doesn't work because hp (which is probably a numeric value, and not an object at all) is not attached to any outside object. Your object is a value in the players array (or players object, doesn't really matter), and you need to mutate that. There's really no way around this.

With that said, I'd write this a little different:

for (var player in players) {
  var p = players[player];
  p.hp = Math.max(p.maxHp, p.hp + 10);
}

If players is an Array, you can even do:

for (var player of players) {
  player .hp = Math.max(player .maxHp, player .hp + 10);
}

Upvotes: 1

Related Questions