Javascript does not have block-level scopes. Instead, javascript uses function scopes. The following example shows how to use javascript scopes in some programming languages similar to C, each piece of code in curly brackets has its own scope, and variables are invisible outside the code segment that declares them. We call them block scope ), javascript does not have block-level scope. Instead, javascript uses function scope: variables are defined in the declared function body and any function nested in the function body. In the following code, I, j, and k defined in different locations are all defined in the same scope.
The Code is as follows:
Function text (o)
{
Var I = 0;
Alert (typeof o );
If (typeof o = "string ")
{
Var j = 0;
For (var k = 0; k <10; k ++)
{
Alert (k); // output 0-9
}
Alert (k); // output 10
}
Alert (j); // output 0
}
The function scope of javascript indicates that all the variables declared within the function are always visible in the function body. Interestingly, this means that the variable is even available before it is declared. This feature of javascript is informal referred to as hoisting. That is, all variables declared in the javascript function body (not involving assignments) are "advanced" to the top of the function body. See the following code
The Code is as follows:
Var global = "globas ";
Function globals ()
{
Alert (global); // undefined
Var global = "hello QDao ";
Alert (global); // hello QDao
}
Due to the function scope feature, local variables are always defined throughout the function body, that is, the variables in the function body cover the global variables with the same name. Even so, when the program executes the var statement, the local variable will be assigned a value. Therefore, the above process is equivalent: the variable declaration in the function is "advanced" to the top of the function body, and the colleague variable initialization stays at the original position:
The Code is as follows:
Var global = "globas ";
Function globals ()
{
Var global;
Alert (global); // undefined
Global = "hello QDao ";
Alert (global); // hello QDao
}