Suppose I setup test2.js as follows
module.exports.doPrint = doPrint;
var dummy = "initial";
function doPrint(callback) {
setInterval(function() {
console.log(dummy);
callback();
}, 1000);
}
I then have test1.js
var test2 = require("./test2");
test2.doPrint(function() {
console.log("changing");
test2.dummy = "new value";
});
When I run test1.js I get the following
initial
changing
initial
changing
In other words the value of dummy in test2.js never gets changed to the new value. Can someone explain what is happening here?
It does not change the value because
dummyis a local variable (can’t be accessed from outside – variables local to the module will be private). To make it work you can changetest2.jsto this:or use:
and
test2.set("new value");to change the value, if you want it to be a local variable.