Global variables are considered bad practice, but I want to use them as a sort of simple "singleton" value.
The following contains three different ways of declaring variables in a global scope in NodeJS (I think). Function change2() succeeds in changing their values from "...one" to "...two". However function change3() does not succed in setting them to "...three".
How can I change the value of a global variable from inside an anonymous function? - I have also tried calling a setter method with no effect. The bind() invocation is just a helpless guess.
global.v1 = 'v1: one';
var v2 = 'v2: one';
v3 = 'v3: one';
function change2() {
global.v1 = 'v1: two';
v2 = 'v2: two';
v3 = 'v3: two';
};
function change3() {
(function() {
global.v1 = 'v1: three';
v2 = 'v2: three';
v3 = 'v3: three';
}).bind({v1:v1, v2:v2, v3:v3});
};
console.log (v1, v2, v3);
change2();
console.log (v1, v2, v3);
change3();
console.log (v1, v2, v3);
output is:
O:\node>node scope
v1: one v2: one v3: one
v1: two v2: two v3: two
v1: two v2: two v3: two
O:\node>
module.exports = {}works even better for a simple singleton. then simplerequire('./v1')in your other modules.change3()you never actually execute the internal function..bind()just returns a new function, but you never actually call it..bind(...)with just()triggered the invocation and "...three" to be set.