0

am try to understand a basic notion in JavaScript.

If somebody has some clarification.

if i has this.

//example: i have storing a default permanente array value with a constructor in: $gameSystem.huds.hudsSlot.default = [10,5]; 
console.log($gameSystem.huds.hudsSlot.default); // return me [10,5]; is nice

//now in a context, i need to store this value in temps var to do some stuff
var test = $gameSystem.huds.hudsSlot.default;
console.log(test): // return me [10,5]; is nice

// but after, if i do 
test[0]++;
// or
test[0]+=1;

console.log(test[0]); // return me 11 ( is ok ) !
//But why 
console.log($gameSystem.huds.hudsSlot.default) // return me 11 ??????
// why test[0]++; or test[0]+=1; increase my objets $gameSystem.huds.hudsSlot.default ???
// why increase my var test[0] increase $gameSystem.huds.hudsSlot.default[0] in same time ?

thanks a lot for help me

jon
  • 1,494
  • 3
  • 16
  • 29
  • 1
    Because your `test` variable is a reference to `$gameSystem.huds.hudsSlot.default` meaning when you change `test`, `$gameSystem.huds.hudsSlot.default` updates to the same value. If you'd like to change the reference to being a unique object, one tactic you could use is `Object.assign`. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign – iamjpg Jan 11 '17 at 01:58
  • I believe OP is saying that (by reference) `console.log(test)` is giving 11, which would indeed be odd.. – Geert-Jan Jan 11 '17 at 02:01
  • @Geert-Jan - not really because both of those calls (test[0]++ and text[0+=1]) are incrementing the zero index of `test` which is the zero reference to `$gameSystem.huds.hudsSlot.default` – iamjpg Jan 11 '17 at 02:03
  • $gameSystem.huds.hudsSlot.default; // need to be static (alway [10,5]) – jon Jan 11 '17 at 02:03
  • 1
    @iamjpg: sure but then this should hold `test = $gameSystem.huds.hudsSlot.default = [11,5]`, instead of `5` as OP says. But perhaps I'm reading too much in to it. – Geert-Jan Jan 11 '17 at 02:08
  • x = Object.assign({},$gameSystem.huds.hudsSlot.default) is work thanks , but what about performance in MS ? – jon Jan 11 '17 at 02:20

0 Answers0