日期:2014-05-16  浏览次数:20362 次

js作用域问题

var scope = "global";

function test(){
 alert(scope);     //undefined?
 var scope = "local";
 alert(scope);    //local
}

test();


请问为什么第一个alert输出的是undefined,而不是global呢?

------解决方案--------------------

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版,你这个例子就是里面的。