为什么这个全局变量在函数内未定义?

Raj*_* Rj 0 javascript

如果在同一个函数中重新声明和定义了相同的全局变量,为什么这个全局变量在函数中未定义?

var a = 1;
function testscope(){
 console.log(a, 'inside func');
 //var a=2;
};
testscope();
console.log(a, 'outside func');

output:
1 "inside func"
1 "outside func" 
Run Code Online (Sandbox Code Playgroud)

考虑相同的代码,其中 var a = 2; 内部功能块未注释

var a = 1;
function testscope(){
 console.log(a, 'inside func');
 var a=2; 
};
testscope();
console.log(a, 'outside func');

Output
undefined "inside func"
1 "outside func"
Run Code Online (Sandbox Code Playgroud)

Adr*_*lat 5

这是因为 Javascript 不像 Java 并且变量声明总是被推到他们的块上。您的第二段代码严格等同于:

var a = 1;
function testscope(){
 var a;  // <-- When executed, the declaration goes up here
 console.log(a, 'inside func');
 a=2;  // <-- and assignation stays there
};
testscope();
console.log(a, 'outside func');

Output
undefined "inside func"
1 "outside func"
Run Code Online (Sandbox Code Playgroud)

  • 请,公然明显的重复需要密切的投票和评论,而不是答案。 (3认同)