如果在同一个函数内重新声明并定义相同的全局变量,为什么该全局变量在函数内未定义?
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"
考虑相同的代码,其中 var a = 2;内部功能 block 未注释
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"
最佳答案
这是因为 Javascript 与 Java 不同,变量声明总是被推到它们的 block 上。您的第二段代码严格相当于:
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"
关于javascript - 为什么这个全局变量在函数内未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47477256/