Scope
Scope is a difficult feature in JavaScript. All object-oriented programming languages have some form of scope, which depends on what context restricts the scope. In JavaScript, scopes are restricted by functions rather than block constraints (such as while, if, and for statement bodies ). In the end, it may make the running results of some code look strange on the surface (if you are from a block-scope language ). The example of Program 2-10 illustrates the meaning of "function scope code.
Code 2-10. example of how variable scope works in JavaScript
// Set a global variable foo equal to "test"
Var foo = "test ";
// In the if Block
If (true ){
// Set foo to "new test"
// Note: this is still in the global scope
Var foo = "new test ";
}
// As we can see here, foo is now equal to "new test"
Alert (foo = "new test ");
// Create a function to modify the variable foo
Function test (){
Var foo = "old test ";
}
// During the call, foo is resident in the function scope.
Test ();
// Confirm that the foo value is still "new test"
Alert (foo = "new test ");
In programs 2-10, you will find that the variables are in the global scope. The interesting side of browser-based JavaScript is that all global variables are actually properties of the window object. Although some earlier versions of operabrowser or Safari browser are not like this, it is generally a good experience rule to assume that the browser works like this. The program 2-11 demonstrates this example.
Program 2-11. Examples of global variables of JavaScript and window objects
// Global variable, including the string "test"
Var test = "test ";
// You will find that our global variables and the test attribute of window are the same
Alert (window. test = test );
Finally, let's take a look at what will happen when a variable is missing definition. In programs 2-12, the variable foo is assigned a value in the scope of test. However, in the 2-12 program, the scope of the variable is not defined (var foo is used. When the foo variable is not clearly defined, it becomes a global variable, even if it is used only in the context of the function.
Program 2-12. Example of implicit global variable Declaration
// A function assigned a value for the variable foo
Function test (){
Foo = "test ";
}
// Call the function to assign a value to foo
Test ();
// We found that foo is a global variable.
Alert (window. foo = "test ");
So far, it should be obvious that although the JavaScript scope is not as strict as the block scope language, it is quite powerful and distinctive. Especially when combined with the closure concept described in the next section, the power of JavaScript will be exposed.