首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

js作用域有关问题

2013-11-16 
js作用域问题var scope globalfunction test(){ alert(scope)//undefined? var scope local al

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

热点排行