0

Lets say I have one variable var car = 'VW' in index.html

index.html is the binding of my application, from there I access several modules:

   <script>
    var car = 'VW';
    var Initializer = require('./js/initializer');
    Initializer.check_requirements();
   </script>

Now in initializer I try to access this variable what does not work.

var Initializer = {
check_requirements: function(){console.log(car)};
};

module.exports = Initializer;

However when I attach the variable car to window:

window.car = 'VW';

Then Im able to access it in my module over window.car;

How do I create an global variable car that I can also access in my modules, so that I do not have to attach to window? Thanks

John Smith
  • 6,105
  • 16
  • 58
  • 109

1 Answers1

2

In a browser context, a "global" variable is in fact a property of the window object, which acts as the global context. The syntax you have in your question, a bare var statement in a script tag in an HTML page, will in fact add that var name as a property to the window. However, since you're using what looks like a CommonJS require statement here, which is not natively supported in most browsers, there's probably a compile step you're not including in your question that's preventing this from working the way you expect.

However, the short answer is, don't do this if you can avoid it. Most applications of global variables are better accomplished with parameters, e.g. Initializer.check_requirements(car);, or in a separate module storing configuration settings, or other approaches.

nrabinowitz
  • 55,314
  • 10
  • 149
  • 165