js中局部变量和全局变量的问题

var scope = 'global' ;
alert(scope);
function testScope(){
alert(scope);
var scope = 'local' ;
alert(scope);
}
这样的三个alert分别是"global","undefined","local"。第二个为什么是未定义啊?

其实你这个代码的效果和下面是一样的:
var scope = 'global' ;
alert(scope);
function testScope(){
var scope;
alert(scope);
scope = 'local' ;
alert(scope);
}
这里就涉及到了,js对变量的处理问题了,js是这样的,无论你在js那里定义变量,它在执行的时候都会变成在开头(函数的开始)就定义所有的变量,但是不赋初始值,所有第二个会alert出 undefined。也是说第二个scope其实是局部变量,但没有初始值。就这样。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-08-04
你能否先说明一下testScope什么时候被调用了追问

就在这个后面加一句testScope()