JavaScript变量作用域

1
2
3
4
5
6
7
var scope = 'globe'; 
function checkscoppe() {
var scope = 'local';
return scope;
}
alert(checkscoppe());//local
alert(scope);//globe

这段代码首先声明了一个全局变量scope,值是globe

然后在函数内声明了一个

1
2
3
4
5
6
7
var scope = 'globe'; 
function checkscoppe() {
var scope = 'local';
return scope;
}
alert(checkscoppe());//local
alert(scope);//globe

这段代码首先声明了一个全局变量scope,值是globe

然后在函数内声明了一个局部变量,声明局部变量一定要使用var!

结果也是理所当然,第一个弹出local

第二个弹出globe

1
2
3
4
5
6
7
var scope = 'globe'; 
function checkscoppe() {
scope = 'local';
return scope;
}
alert(checkscoppe());
alert(scope);

这段代码只是把函数内部的var去掉后就会导致函数内部scope覆盖全局变量,所以两个alert都是local