我刚遇到这种情况:
var testing = 'thing 1';
function func() {
console.log(testing);
var testing = 'thing 2';
console.log(testing);
}
func();
我希望上面的代码记录 'thing 1'
,然后才记录 'thing 2'
。但是,永远不会记录 'thing 1'
。
起初我认为将 testing
变量保留在其范围内可能是静态函数的某些行为,因此它是 undefined
而不是 'thing 1 '
.
但是,如果我自己的解释(最初看起来正确)是否有效,我也不确定它是否真的是一个静态函数。
为什么testing
变量在func
里面是undefined
?为什么 func
不能访问全局变量?还有其他类似的情况吗?
PS:我试图找到一个骗子,但失败了。
最佳答案
您无法获得 thing 1
的原因是因为您在 testing
具有本地的同一范围内调用 testing
定义。所有声明都是 "hoisted" 到它们封闭范围的顶部,所以即使你写了:
var testing = 'thing 2';
在您的第一个 console.log()
之后,var testing
被提升并作为函数中的第一段代码进行处理,因此 testing
已在本地声明,但尚未初始化(这将发生在该行的原始位置)。
所以,您的代码流程如下:
var testing = 'thing 1'; // 1. Runs as soon as encountered
function func() {
var testing; // 3. testing is hoisted and declared, but still undefined
console.log(testing); // 4. undefined is logged
testing = 'thing 2'; // 5. local `testing` is now initialized
console.log(testing); // 6. local `testing` is logged "thing 2"
}
func(); // 2. func is invoked
拥有多个具有相同标识符(名称)的变量是完全可以的(但有时会令人困惑),但您必须了解的是,总是首先检查较小的范围,因此从 func
内部,当您要求 testing
时,您将获得在该功能期间“隐藏”全局版本的本地版本。
全局变量被称为全局变量,因为您可以随时访问它们。如果你想要全局版本,你总是可以将它作为全局 window
对象的属性来访问:
var testing = 'thing 1';
function func() {
console.log(testing);
var testing = 'thing 2';
console.log(window.testing);
}
func();
关于javascript - 什么情况下函数不能访问全局变量?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44851068/