1

In my app i have two modules, which both need one object variable, but in them, they alter its content slightly:

In app.js

var example = {title: "test"};
var admin = require('./admin');
var research = require('./research');
admin.data(example);
research.data(example);
console.log(admin.get());
console.log(research.get());

In research.js

var datasnapshot = null;
module.exports = {data: updateData, get: getData};
function updateData(data) {
    datasnapshot = data;
}
function getData() {
    return datasnapshot
}

In admin.js

var datasnapshot = null;
module.exports = {data: updateData, get: getData};
function updateData(data) {
    datasnapshot = data;
    datasnapshot.title = "Admin Panel";
}
function getData() {
    return datasnapshot
}

The problem is, that botch console.log() return me {title: "Admin Panel"}, despite the fact, that i only want it to be like so in second module. Thank you in advance for assistance!

1 Answers1

1

The problem is, that botch console.log() return me {title: "Admin Panel"}

Because you are passing the same object to both the modules, so when the second module updates the value, it is reflected in the first module as well.

that i only want it to be like so in second module

If you want to ensure that each of the respective modules should use their own copy of the example object then modify your updateData methods to

//for research.js
function updateData(data) {
    datasnapshot = JSON.parse(JSON.stringify(data)); //deep copying the object
} 

//for admin.js
function updateData(data) {
    datasnapshot = JSON.parse(JSON.stringify(data)); 
    datasnapshot.title = "Admin Panel";
}

There are other methods of deep copying the object share here

gurvinder372
  • 66,980
  • 10
  • 72
  • 94