In some C-like programming languages, each piece of code in curly braces has its own scope, and variables are invisible outside of the code segment that declare them. We call block scope, and there is no block scope in JavaScript. Instead, JavaScript uses function scope: variables are defined in the function body that declares it and any function body nested in the function body. In the following code, i, j and k defined in different locations are defined within the same scope.
The code copy 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
}
JavaScript's function scope means that all variables declared inside a function are always visible in the function body. Interestingly, this means that the variables are even available before they are declared. This feature of javascript is informally called hoisting, that is, all variables declared in the function body of javascript (no assignment involved) are "advanced" to the top of the function body. Look at the following code
The code copy is as follows:
var global="globas";
function globals()
{
alert(global);//undefined
var global="hello QDao";
alert(global);//hello QDao
}
Due to the nature of function scope, local variables are always defined throughout the function body, which means that the variables inside the function body cover global variables with the same name. Despite this, local variables will be truly assigned when the program executes the var statement. Therefore, the above process is equivalent to: declaring the variables in the function "advance" to the top of the function body, and leaving the initialization of the colleague variables in the original position:
The code copy is as follows:
var global="globas";
function globals()
{
var global;
alert(global);//undefined
global="hello QDao";
alert(global);//hello QDao
}