简体   繁体   中英

Assign value of global variable to object

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?

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] );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM