JavaScript中全局变量与window变量的区别及存储位置咨询
window对象与ES6声明方式的区别 Great question—this is a super common point of confusion when transitioning from ES5 to modern JavaScript, so let’s break it down nice and clearly.
1. var声明的全局变量:直接绑定到window对象
In the browser environment, pre-ES6 JavaScript tied the global scope directly to the window object. When you declare a global variable with var, it automatically becomes a property of the window object:
var a = 1; alert(window.a); // 弹出 '1'
This is legacy behavior from early JS, where the global context and the browser’s top-level window object were essentially one and the same.
2. let/const声明的全局变量:独立于window
ES6 introduced let and const to fix many of var’s odd behaviors, and one key change is how global variables are stored. When you declare a global variable with let or const, it does not become a property of the window object:
let b = 1; alert(window.b); // 弹出 'undefined'
So where does b live? It’s stored in the declarative environment record of the global scope. Modern JavaScript’s global scope has a split environment record with two parts:
- The object environment record: Linked directly to the
windowobject, this holds allvar-declared global variables and built-in global properties (likewindow.alert). - The declarative environment record: A separate, isolated container that holds
let/const-declared global variables and class declarations. It’s part of the global scope, but you can’t access it via thewindowobject.
You can confirm b is still in the global scope by accessing it directly:
console.log(b); // 输出 1
3. 存在两个独立的全局命名空间吗?
Nope, there aren’t two distinct global namespaces. Instead, the global scope now uses a split environment record to manage different types of declarations. Think of it as one global context with two "storage bins": one tied to window for legacy code, and an isolated one for modern ES6 declarations. They’re part of the same global scope—just stored differently.
A quick side note for Node.js users: The browser’s window doesn’t exist here; instead, there’s a global object. Similar rules apply though: var-declared globals become properties of global, while let/const globals don’t (they live in the module’s top-level scope or the global environment record, depending on context).
内容的提问来源于stack exchange,提问作者kadina

