1

Lets say I have a variable:

<script type="text/javascript">
    var myVariable = "something";
</script>

After this js global variable declaration I have another javascript:

<script type="text/javascript" src="myScriptFile.js"></script>

In this file I need to use the value of my global myVariable variable. I know that I can do it by setting this value in some HTML, then using DOM or jQuery or something else get this value in the file, but I want to avoid creating those kind of hidden fields in my HTML. Is there any better way to do this?

putvande
  • 15,068
  • 3
  • 34
  • 50
user2219247
  • 1,313
  • 10
  • 20
  • 26
  • You can set the variable on the `window` object instead from any external file: `window.myVariable = "something";`, then you just need to make sure it gets set before you use it in `myScriptFile.js` – CodingIntrigue Aug 28 '13 at 08:22
  • 1
    @RGraham It's already added to the window object. No need to set it explicitly. – Johan Aug 28 '13 at 08:23

4 Answers4

5

Make it global;

script1.js

 var foobar = "O HAI";

script2.js

  alert(foobar);
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
2

Anything that you will put in window in any place (even in functions) will be visible in global scope. So

<script type="text/javascript">
    window.myVariable = "something";
</script>

And myVariable will be visible anywhere

redexp
  • 4,765
  • 7
  • 25
  • 37
1

I use global variables with

jQuery.data(document.body, "varAgrup", { var1: value1, var2: value2 });

I get var value with

jQuery.data(document.body, "varAgrup").var1;
0

You can use the global variable in the myScriptFile.js file if it was defined before the script which will use it on the same page.

Alexandr Mihalciuc
  • 2,537
  • 15
  • 12