views:

1119

answers:

3

If I include a JavaScript file in my HTML page, do the variables declared in my JavaScript file also have scope in my <script /> tags in my HTML page? For example, in my included JS file, I declare a variable:

var myVar = "test";

Then inside my HTML page, what will this produce (if it's after my include script tag)?

alert(myVar);
+8  A: 

If you declare the variable outside of any function as

var myVar = 'test';

or at any location as

myVar = 'test';

or

window.myVar = 'test';

It should be added to the Global Object (window) and be available anywhere as

alert(myVar);

or

alert(window.myVar);

or

alert(window['myVar']);
Barry Fandango
Even with an included JavaScript file?
Brandon Montgomery
Yup. Try it out:test.html:<html> <head> <script type=text/javascript src=test.js></script> </head> <body onload="alert(test);"> </body></html>test.js:var test = 'hello!';put those two files in the same folder and load the html page. it works!
Barry Fandango
hmm that didn't format very nicely, but i hope you get the idea.
Barry Fandango
+2  A: 

It will produce an alert containing "test".

All variables declared at the top level in JavaScript share the same scope. If you want to use variables in one file that won't clash with another, then you can use an anonymous function to introduce a new scope:

var myVar = "something else";
(function () {var myVar = "test"; alert(myVar)})();
alert(myVar);

edit: As BYK points out, you can expand this into something that resembles a full fledged namespace, by assigning an object literal:

var MyNamespace = (function () {
  var myVar = "something";
  return { alert: function() { alert(myVar) },
           setVar: function(value) { myVar = value } }
})();
Brian Campbell
You can also use a "namespace" which simply is a static Object for grouping your variables and functions.
BYK
A: 

When you declare a variable or a function in your code, you're creating a property of window. Consider these examples:

var a = 'Cow';
alert(window.a); // Cow
alert(this.a); // Cow
alert(a); // Cow

If you declare a variable inside a function, your variable won't be accessible from outside of it unless you add it to the window object:

function lalala() {
    alert(a); // still Cow
    a = 'Pig'; // We're tired of cows by now. Let's make it a pig.
    var b = 'Sheep';
}
lalala();
alert(a); // Pig
alert(b); // undefined, since b is declared in the lalala scope

Thus, your example would alert test.

moff