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 dummy
is a local variable (can't be accessed from outside - variables local to the module will be private). To make it work you can change test2.js
to this:
module.exports.doPrint = doPrint;
function doPrint(callback) {
var that=this;
this.dummy = "initial";
setInterval(function() {
console.log(that.dummy);
callback();
}, 1000);
}
module.exports.doPrint = doPrint;
module.exports.get = get;
module.exports.set = set;
var dummy = "initial";
function get(){
return dummy
}
function set(new_value){
dummy=new_value;
}
function doPrint(callback) {
setInterval(function() {
console.log(dummy);
callback();
}, 1000);
}
and test2.set("new value");
to change the value, if you want it to be a local variable.