javascript---variable scope

the global and local scope are just as the names ,it is not worth to discuss what do they represent,but some special characters should be necessary for programmer to remember.

    in last topic ,I said that if  we declarea variable without var and assign a value to it ,the variable will be a local variable.someting unacceptable result will do if we explicitly declare a global variable without  var ,then declare a variable in a local scope(in a function)  also without var(as we know it will be a global variable),what 's more ,the local variable and global variable have the same name.if so,the local scope variable will change the value of the global variable with it own value.example:

 

代码
   
     
scope = " global " ; // explicity global variable without var
function checkscope() {

scope
= " local " ; // will replace the global variable
alert(scope); // alert "local"

}
window.onload
= function ()
{
checkscope();
alert(scope);
// alert local,the value has been changed to "local"
}

so it is very important to declare a variable with var,I think it is a must.

 

No Block Scope

first ,let us check some C# code

  
    
public void TestCSharp()
{
// we can't access i and j here
for ( int i = 0 ;i < 10 ;i ++ )
{
int j = i;
}
// we can't access i and j here too
}

but in javascript, all variables declared in a function ,no matter where they are declared, are defined throughout the function,let us check the following javascript code;

代码
   
     
window.onload = function () {
var i
= 0 ;
if ( 1 == 1 ) {
var j
= 0 ;
for (var k = 0 ; k < 1 ; k ++ ) {
alert(k);
}
alert(k);
// k has been out of the for block scope
}
alert(j);
// j has been out of the if block scope
}

the feature may cause some surprising results,if there is a local variable have the same name with the global variable.

 

  
    
var scope = " global " ;
window.onload
= function () {
alert(scope);//first alert
var scope = " local " ;
alert(scope);//second alert
}

you just as me first may think the first call to alert() would display "global",because the local definition has not yet been executed.however,after my test,I found that the first call to alert() display "undefined",why??

    let us discuss deeply,because the no block scope rules in javascript,the variable defined in a function is thoughtout the function.so previous example is equivalent to the following:

 

代码
   
     
var scope = " global " ;
window.onload
= function () {
var scope;
alert(scope);
// alert undefined,scope is just a unassigned variable.
var scope = " local " ;
alert(scope);
}

 

so I know what has happened.

oh,so late ,time to sleep,so tired!

你可能感兴趣的:(JavaScript)