I have a JavaScript array inside a namespace like this:
app.collec.box = [];
and I have a function inside the same namespace like this:
app.init = function () {
var box = this.collec.box;
// ... code to modify box
};
I thought that setting a local variable equal to an object or object property was just a REFERENCE to the original, but it seems I am wrong, after changing the contents of the local box variable inside my function, app.collec.box does not change.
Please help, what am I doing wrong? how can I solve this?
Thanks in advance.
EDIT. This is the complete code.
var app = {
collec: {
box: [],
cache: []
},
init: function () {
var box = this.collec.box;
$.ajax({
url: 'file.json',
success: function (json) {
// Map JSON array to box array using Underscore.js _()map
box = _(json).map(function (o) {
return new Model(o);
});
}
});
}
};
app.init();
References point to objects, not variables.
boxis not a reference to the variablethis.collec.box; rather,boxandthis.collec.boxare references to one specific object in memory. You can modify the properties of this object through either of these variables, but you can’t use one variable to modify another variable.If you want to modify what
this.collec.boxrefers to, you either need to set it directly like this:or use a reference to the
this.collecobject and modify itsboxproperty:Edit: Maybe a couple of diagrams will make it easier to understand what’s happening.
When you assign
box = this.collec.box, this is what actually happens:Both the variables point to the same object in memory, but in no way does
boxactually refer to thethis.collec.boxvariable.What you are expecting would work if this happened:
but this doesn’t happen.