Javascript: passing objects by reference

In my applications, I'm not sure if I duplicate data when I pass it to other objects. As an example, 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 the plugin, the data property from dataStore is passed to it. Then it is assigned to the property inside the plugin. Bearing in mind that the transmitted data is an object, to my question, is this the creation of two variables in memory, or is the data property in the plugin referencing a property in the DataStore object?

If it does not save the link after the assignment, how can I pass the DataStore to plugins and save the link to it locally? Or do I need to save the DataStore as a global variable in my application area and reference it globally from plugins?

+4
source share
2 answers

Both dataStore.data and plugin.data refer to the same object - mutation of the object in any of these "classes" (due to the lack of a better term) will lead to mutation of the object for both of them (since both of them contain references to the same and same object).

+11
source

Function arguments are always passed by reference in JS. When you pass an object as an argument, what is being passed is actually a pointer to the location of the object in memory. If you try to rewrite the link, nothing will happen to the original object, however if you change the value of any of the properties of the object, the original object will be changed.

Example:

 function f1(_x) { _x = 5; } function f2(_y) { _y.name = 'Hello'; } var x = 10; f1(x); console.log(x); // no change to x var y = {name: 'Tom'}; f2(y); console.log(y.name); // y.name is now Hello 
0
source

All Articles