Code List 1-1: An Example of javascript variable scope
// Set the global variable foo to "test"
Var foo = "test ";
// In the if Block
If (true ){
// Set foo to 'new Test'
Var foo = "new test ";
}
// As we can see, foo is now 'new Test'
Alert (foo = "new test ");
// Create a new function that will modify the variable foo
Function test (){
Var foo = "old test ";
}
// However, when calling, foo only works within the function Scope
Test ();
// Check whether foo is equal to 'new test'
Alert (foo = "new test ");
An interesting feature of browser-based javascript is that all variables in the global variable scope are actually properties of the window object.
Code List 1-2 global scope and window object in javascript
// A global variable that stores the string 'test'
Var test = 'test ';
// You can see that our global variables are 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 be used within the scope of this function.
Code List 1-3 implicit global scope variable Declaration
// A function with the foo value set
Function test (){
Foo = "test ";
}
// Call this function to set the value of foo
Test ();
// We found that foo is under the global scope.
Alert (window. foo = "test ");