2

I have a array of object, in which I need to assign unique id. To make it simple, I declared a global var for this id, that I update at every new object:

var id_unit = 0,
    units = [],
    merc = [
        {name: 'grunt',     id: 0, level: 1, hp: 1, atk: 1, def: 1, deployed: false},
        {name: 'big grunt', id: 0, level: 1, hp: 1, atk: 1, def: 1, deployed: false}
    ];

function buy_unit(type, callback) {
    var unit = merc[type];
    unit.id = id_unit;//0 + id_unit //new Number(id_unit) //Number(id_unit)
    id_unit = id_unit + 1;
    units.push(unit);
    callback('OK');
}

Problem is, when I use this function, id seems to have got the adress of unit_id instead of its value:

buy_unit
unit_id: 0
i: 0    id: 0   level: 1        deployed: false

buy_unit
unit_id: 1
i: 0    id: 1   level: 1        deployed: false
i: 1    id: 1   level: 1        deployed: false

When what I was expecting was:

buy_unit
unit_id: 1
i: 0    id: 0   level: 1        deployed: false
i: 1    id: 1   level: 1        deployed: false

Why is unit_id returning its pointer and not its value? How can I get the value?

EML
  • 9,619
  • 6
  • 46
  • 78
DrakaSAN
  • 7,673
  • 7
  • 52
  • 94
  • Is the real code inside a loop, so that `id_unit` is being captured in a closure? See http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – RichieHindle Jun 09 '15 at 11:13

1 Answers1

4

This doesn't create a copy of the object:

var unit = merc[type];

It just makes unit refer to the same object as merc[type], so if you assign to unit.id you are changing the id property of a unit in your merc array.

It seems like you want to use your merc[type] as the prototype for a new object:

var unit = Object.create( merc[type] );
Paul
  • 139,544
  • 27
  • 275
  • 264