nodejs中函数外的json变量的作用域是什么?
What is the scope of json variable outside the function in nodejs?
考虑下面的代码片段,
function(){
if(condition){
var json = { "stat":"success","count":"3" };
}
}
console.log(json);
return json;
这里 json 不应该给出正确的值,因为它的范围已经结束,但我实际上可以得到 json 值。谁能告诉我这是怎么回事?
如果你的意思是这样的(实际上 运行 的代码):
function test(){
if(condition){
var json = { "stat":"success","count":"3" };
}
console.log(json);
return json;
}
test();
您正在使用 var
。 var
创建一个具有函数作用域而不是块作用域的变量。因此,您的代码等同于:
function test(){
var json = undefined; // variable is function scoped
if(condition){
json = { "stat":"success","count":"3" };
}
console.log(json); // can access here, may have undefined value
return json;
}
test();
如果您使用 let
或 const
而不是 var
,那么您的变量将是块范围的,这会产生错误:
function test(){
if(condition){
let json = { "stat":"success","count":"3" };
}
console.log(json);
return json;
}
test();
因为用 const
或 let
声明的 json
变量仅在您创建它的块范围内可用,并且 console.log(json)
和 return json
都会因尝试引用不再存在的变量而产生错误。
考虑下面的代码片段,
function(){
if(condition){
var json = { "stat":"success","count":"3" };
}
}
console.log(json);
return json;
这里 json 不应该给出正确的值,因为它的范围已经结束,但我实际上可以得到 json 值。谁能告诉我这是怎么回事?
如果你的意思是这样的(实际上 运行 的代码):
function test(){
if(condition){
var json = { "stat":"success","count":"3" };
}
console.log(json);
return json;
}
test();
您正在使用 var
。 var
创建一个具有函数作用域而不是块作用域的变量。因此,您的代码等同于:
function test(){
var json = undefined; // variable is function scoped
if(condition){
json = { "stat":"success","count":"3" };
}
console.log(json); // can access here, may have undefined value
return json;
}
test();
如果您使用 let
或 const
而不是 var
,那么您的变量将是块范围的,这会产生错误:
function test(){
if(condition){
let json = { "stat":"success","count":"3" };
}
console.log(json);
return json;
}
test();
因为用 const
或 let
声明的 json
变量仅在您创建它的块范围内可用,并且 console.log(json)
和 return json
都会因尝试引用不再存在的变量而产生错误。