如果在同一个函数中重新声明和定义了相同的全局变量,为什么这个全局变量在函数中未定义?
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)
这是因为 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)
| 归档时间: |
|
| 查看次数: |
1775 次 |
| 最近记录: |