Klaus Hildner
Klaus Hildner

Reputation: 1

node.js: how to set global variable from within anonymous function?

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>

Upvotes: 0

Views: 3956

Answers (1)

jfriend00
jfriend00

Reputation: 707308

In change3() you never actually execute the internal function. .bind() just returns a new function, but you never actually call that new function.

If you want to call it, you'd have to add parens after the .bind():

function change3() {
   (function() {
       global.v1 = 'v1: three';
       v2 = 'v2: three';
       v3 = 'v3: three';
   }).bind({v1:v1, v2:v2, v3:v3})();   // add parens at the end here
};

But, you don't even need the .bind() here as it isn't helping you.

function change3() {
   (function() {
       global.v1 = 'v1: three';
       v2 = 'v2: three';
       v3 = 'v3: three';
   })();   // add parens at the end here
};

Upvotes: 1

Related Questions