我正在努力了解 JavaScript 中的提升和作用域,并试图弄清楚这段代码中到底发生了什么。 console.log(outside)
和 console.log(local)
都记录未定义,如我所料,因为 outside
已声明但未初始化,并且 local
的声明被提升到函数的顶部。但是为什么typeof global
等于'undefined'
。在函数内省(introspection)略 var
是否与在全局范围内声明变量相同 - 在这种情况下它不会被提升?
var outside;
(function() {
i = 2;
if (i == 1) {
var local = 'local';
global = 'global';
}
// Demonstrates that local variables are hoisted but global variables are not.
console.log(outside); // undefined
console.log(local); // undefined
console.log(global); // Uncaught ReferenceError: global is not defined. (i.e. typeof global === 'undefined')
})();
最佳答案
首先,只有用 var
定义的变量会被提升。
赋值给一个以前没有声明过的变量会在赋值发生时创建一个同名的全局变量。
尝试读取之前未声明的变量会导致引用错误,除非您在其前面加上包含对象(例如 window.global
),在这种情况下,它将返回与任何其他属性相同的值尚不存在的对象,未定义
。
您的代码基本上等同于此(添加了一个 console.log() 语句):
var outside; // declared as a global
(function() {
var local; // the declaration of this variable is hoisted to here
i = 2;
if (i == 1) {
local = 'local';
global = 'global'; // creates a global variable only when this line is executed
}
console.log(outside); // undefined
console.log(local); // undefined
console.log(window.global); // undefined
console.log(global); // Uncaught ReferenceError, no symbol of this name is found
})();
这意味着 outside
和 local
都是在您尝试使用它们时定义的,因此没有引用错误。两者都未初始化,因此它们的值为 undefined
。 global
在您尝试引用它时未定义,因为您对它的分配未执行,因此它不存在。使用 var
不会提升创建全局变量。只有在分配给它们的代码实际执行时才会创建这些变量。
关于javascript - 提升没有声明为 'var' 的 JS 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24902475/