Code Listing 1-1 Example showing the variable scope of JavaScript
//Set the global variable foo and set it to "test"
var foo = "test";
//In the if block
if(true){
//Set foo to 'new test'
var foo = "new test";
}
//As we can see, now foo is equal to 'new test' '
alert(foo == "new test");
//Create a new function that will modify variable foo
function test(){
var foo = "old test";
}
//However, when called, foo only works within the function scope
test();
//This confirms that foo is still equal to 'new test'
alert(foo = = "new test");
An interesting feature of browser-based JavaScript is that all variables belonging to the global variable scope are actually properties of the window object.
Code List 1-2 Global scope and window object in javascript
//A variable under the global scope stores the string 'test'
var test = 'test';
/ /You can see that our global variable is consistent with the test attribute of the window object
alert(test == window.test)
Finally if the variable is not explicitly defined, it is globally defined, although it may Only used within the scope of this function.
Code Listing 1-3 Implicit global scope variable declaration
//A function that sets the value of foo
function test(){
foo = "test";
}
//Call this function to set the value of foo
test();
//We find that foo is now in the global scope
alert(window.foo == "test");