0

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>
3
  • 1
    not a direct answer, but a file "v1.js" with contents module.exports = {} works even better for a simple singleton. then simple require('./v1') in your other modules. Commented Nov 26, 2016 at 4:39
  • In change3() you never actually execute the internal function. .bind() just returns a new function, but you never actually call it. Commented Nov 26, 2016 at 4:43
  • Thanks @jfriend00 for spotting. Replacing .bind(...) with just () triggered the invocation and "...three" to be set. Commented Nov 26, 2016 at 5:20

1 Answer 1

1

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
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.