1

I stumbled over a strange thing.

I have a model class where you can get values of attributes via a model.get(attributeName) function.

So I did this in a view:

var mapModel = new Ex.Models.MapModel(model);
var view = new Ex.Views.MapView(mapModel);

var d = this.model.get('layerIds');
d.mapLayer = view.getId();

console.log("layerIds", this.model.get('layerIds'));

The attributes layerIds.mapLayer is set to null by default. If I set it to the views id (e.g. 43) I'd expect that the console.log would still return {mapLayer: null} since I create varaible d to copy the value of this.model.get('layerIds') and work with that value independent from the models value.

But if I execute this piece of code the log says:

{mapLayer: 43}

Why is this? Why do Javascript variables keep track of their copied values and update their own value if one of the others changed?

And how can this be stopped?

Johannes Klauß
  • 10,676
  • 16
  • 68
  • 122

2 Answers2

1

The get method in the proceeding line returns a reference to the layerIds object within the model:

var d = this.model.get('layerIds');

When the maplayer property on d is set the reference is also manipulated. Basically d and this.model.get('layerIds') will return the same object from memory.

d.mapLayer = view.getId();

If you checked equality between the two you will notice they are the same object.

d === this.model.get('layerIds') // true

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
1

From Javascript by reference vs. by value:

"Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object."

this.model.get('layerIds'); //  returns an object : {mapLayer: null}
Community
  • 1
  • 1
nioKi
  • 1,259
  • 9
  • 17
  • 1
    Also, one cannot observe that this is not true for primitives as well because you cannot attach or modify properties of primitives in the first place. – Esailija Aug 06 '13 at 09:53