var scope = "global";function test(){
 alert(scope);     //undefined?
 var scope = "local";
 alert(scope);    //local
}test();
请问为什么第一个alert输出的是undefined,而不是global呢?

解决方案 »

  1.   

    js在函数里定义的变量可以在函数里的任意位置访问,甚至定义前的位置 
    你的方法其实函数里定义的scope已经在方法里覆盖掉了外边的scope  而此时scope又没赋值  所以undefined
      

  2.   

    以后这样写
    function test(){
    var scope = "local";
     alert(scope);     //undefined?
     
     alert(scope);    //local
    }
    不要这样写
    function test(){
     alert(scope);     //undefined?
     var scope = "local";
     alert(scope);    //local
    }
    何必自扰
      

  3.   


    var scope = "global";function test(){
     alert(scope);     //undefined?
     var scope = "local";
     alert(scope);    //lcal
    }test();因为函数外面的那个叫全局变量,函数内部的叫局部变量,函数内部局部变量最大,因此它会覆盖掉全局变量。
    你写的内部函数相当于;
    var scope;
    alert(scope);
    scope="local";
    alert(local);
    参见JS权威指南第6版,你这个例子就是里面的。