您的位置:首页 > Web前端 > JavaScript

关于JavaScript作用域的练习题

2015-12-23 15:17 621 查看
var y = 'global';
function test(x){
if(x){
var y ='local';
}
return y;
}
console.log(test(true));

输出:local

与C++所不同的是,JavaScript中的作用域是函数作用域,而不是块级作用域,
第一句话中的y的作用域是全局,而函数中y的作用域是test函数,上面的程序会返回test中的y,故输出local

var y = 'global';
function test(x){
(function(){
if(x){
var y = 'local';
}
})();
return y;
}
console.log(test(true));

输出:global

var y = 'local'这一句中y的作用域是匿名函数,故返回全局变量global

var y = 'global';
function test(x){
{
if(x){
var y = 'local';
}
}
return y;
}
console.log(test(true));

输出:local

与第一道题目一样,函数中的y作用域在是test函数,故输出global

var y = 'global';
function test(x){
console.log(y);
if(x){
var y = 'local';
}
return y;
}
console.log(test(true));

输出:
undefined
local

这里涉及到JavaScript中的变量提升,JavaScript中会自动把变量生命的语句提升到当前作用域的最前方
以上代码可以这样来理解
var y = 'global';
function test(x){
var y;
console.log(y);
if(x){
y = 'local';
}
return y;
}
console.log(test(true));
注意,当test函数中打印y时,变量y只是被声明了,并没有赋值,所以打印出了undefined;
当程序继续向下执行,输出local

var y = 'global';
function test(x){
console.log(y);
var y = 'local';
return y;
}
console.log(test(true));

输出:
undefined
local

var a = 1;
function b(){
a = 10;
return;
var a = 100;
}
b();
console.log(a);

输出:1

这里先执行了函数b,然而函数b中对a值的改变不会影响到全局变量
故输出全局变量a = 1.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript