我的本地范围有问题。第二个console.log不显示“a”值,但显示未定义。为什么这样?
"use strict"
console.log(a); //undefined
var a = "a";
function b(){
console.log(a); // why is undefined here?
var a = "a1";
console.log(a); // here is "a1"
}
b();
最佳答案
JS 将处理您的代码,如下所示:
"use strict"
var a; // undefined
console.log(a); //undefined
a = "a";
function b(){
var a; // undefined
console.log(a); // all is clear, LOCAL variable a is undefined.
a = "a1";
console.log(a); // here is "a1"
}
b();
了解有关吊装的更多信息 here .
您还可以阅读 Function declaration hoisting ,这也是 JavaScript 基础知识的重要组成部分。
关于javascript - 为什么局部作用域不引用全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36859932/