Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Passing objects by reference

In my applications I am not sure if I am duplicating data when I pass it around to different objects. Just as an example have a look at the following code:

var DataStore = function(data) {
    this.data = data; // <-- typeof data === 'object'
}

var Controller = function() {
    var dataStore = new DataStore({foo: 'bar'});
    var plugin = new Plugin(dataStore.data);
}

var Plugin = function(data) {
   this.data = data;
}

var app = new Controller();

When I create Plugin it is passed the data property from dataStore. It is then assigned to a property inside Plugin. Keeping in mind that the data being passed around is an object my question is, is this creating two variables in memory or does the data property in Plugin reference the property in the DataStore object?

If it doesn't keep the reference after assignment, how can I pass the DataStore into Plugins and keep a reference to it locally? Or would I need to keep DataStore as a global variable in my application scope and reference it globally from the plugins?

like image 649
Seain Malkin Avatar asked Dec 20 '22 18:12

Seain Malkin


1 Answers

Both dataStore.data and plugin.data reference the same object - mutating the object in either of these "classes" (for lack of a better term) will result in the object being mutated for both of them (since they are both holding references to the same object).

like image 198
Sean Vieira Avatar answered Dec 28 '22 12:12

Sean Vieira