js中变量作用域的小理解

一:变量作用域

在js代码中每个变量都是有自己的作用域的,js中不像C语言有块级作用域的概念,取而代之的是函数作用域,看如下代码:

var scope="global";
function init(){
alert(scope);
var scope = "local";
alert(scope);
}
function testScope(){
alert(scope);
}

在上述代码中第一个scope输出的是undefined,第二个scope输出的是local,第三个scope中输出的是global。我们首先分析var scope="global";这个是一个全局变量,var scope = "local";这个是一个局部变量作用域在函数init体内,但是js中的声明函数是先声明后赋值的,并且声明永远置顶,并且在函数体内如果存在变量名称与全局变量名称相同会优先取局部变量,因此上面的代码可以修改为:

var scope="global";
function init(){

var scope;
alert(scope);
scope = "local";
alert(scope);
}
function testScope(){
alert(scope);
}

基于以上代码就可以得出之前的结论。

但是注意一下,如果代码变成如下:

var scope="global";
function init(){

alert(scope);
scope = "local";
alert(scope);
}
function testScope(){
alert(scope);
}

那么输出结果会global,local,local。因为在函数体内,如果变量不用var声明,那么这个变量就是全局变量,会覆盖掉之前var scope="global";声明的全局变量,因此会在testScope函数中值会变成local。

 

因此,在实际编码中建议将变量声明放在函数顶部,而不是靠近使用这个变量的地方,这样对函数的作用域会有清晰的认识。

posted @ 2017-01-05 13:54  迷途小码猿  阅读(288)  评论(0编辑  收藏  举报