/* Code 1 */
var scope = "global " ;
function checkScope() {
var scope = "local ";
function childCheck() {
var scope = "childLocal ";
document.write(scope);
}
function childUndefined() {
document.write(scope);
var scope;
}
function childOverride() {
scope = "childOverride ";
document .write(scope);
}
document.write(scope); //Output "local"
childCheck(); //Output "childLocal"
childUndefined(); //Output" undefined"
childOverride(); //Output "childOverride"
document.write(scope); //Output "childOverride"
}
checkScope(); //Output "local childLocal undefinedchildOverride childOverride "
document.write(scope); //Output "global "
Global scope and local scope
The scope of global (global) variables is global, in Javascript There are definitions everywhere; the variables declared inside the function are local variables, their scope is local, and they are only defined inside the function body. The following output should come as no surprise to readers.
/* Code 2 */
var scope = "global";
function checkScope() {
var scope = "local";
document.write(scope);
}
checkScope(); //Output "local"
document.write(scope); //Output "global"
You can use variables in the global variable scope without the var statement, but you must use the var statement when declaring local variables, otherwise it will Treated as a reference to a global variable. Look at the code below:
/* Code 3 */
var scope = "global";
function checkScope() {
scope = "local";
document.write(scope);
}
checkScope(); //output" local"
document.write(scope); //Output "local"
No block scope
Javascript does not have block-level scope, variables declared in the function are in the entire function They are all defined. The following code may be surprising to unfamiliar readers:
/* Code 4 */
var scope = "global";
function checkScope() {
document.write(scope); // Statement 4.1
var scope = "local"; / /Statement 4.2
document.write(scope);
}
checkScope(); //Output "undefinedlocal"
Due to statement 4.1 (var scope = "local"; ) The variables declared are valid within the entire checkScope function scope, so when statement 4.2 (document.write(scope); ) is executed, the scope refers to the local variable, and the local variable scope is not yet defined at this time, so "undefined" is output. . Therefore a good programming practice is to group all variable declarations at the beginning of the function.
After understanding the above content, readers should not be confused when looking at Code 1.
Attribute variables of objects
Attribute variables of objects are relatively easy to understand. Readers should not be confused if they look at the code below.
/* Code 5 */
var scope = "global ";
var obj = new Object();
obj.scope = "object ";
obj.checkScope = function () {
var scope = "loacl ";
document.write(scope); //Output "loacl"
document.write(this.scope); //Output "object"
document.write(window.scope); //Output "global"
}
obj.checkScope(); //Output "loacl object global"