全局let变量存储在哪里? [英] Where are global let variables stored?
问题描述
我已经在全局范围内创建了一个导航器变量,并使用let
关键字为其分配了一个字符串.
I have created a navigator variable in global scope and assign it a string using let
keyword.
// in a browser
let navigator = "Hello!";
console.log(navigator ); // "Hello!"
console.log(window.navigator === navigator ); // false
此处let navigator
值遮盖了window.navigator
.但是我很好奇let navigator
到底存储在哪里?
Here let navigator
value shadows the window.navigator
. But I am very curious to know where exactly the let navigator
gets stored in?
推荐答案
由于您使用的是let
而不是var
,因此它将存储在声明性的词汇环境对象,而不是全局对象本身.环境记录和词法环境对象是规范机制,不能直接在代码中访问(因此,它们的实际实现可能会因JavaScript引擎而异).
Because you used let
rather than var
, it gets stored in the declarative environment record associated with the global lexical environment object, rather than on the global object itself. Environment records and lexical environment objects are specification mechanisms and not directly accessible in code (and thus the actual implementations of them can vary depending on JavaScript engine).
这是一个概念—不是全局对象属性的全局变量是从ES2015开始引入的新事物;在此之前,所有全局变量都是全局对象的属性.从ES2015开始,全局级别的let
,const
和class
标识符绑定不保存在全局对象上,而是保存在单独的声明性环境记录上.
This is a concept — globals that aren't properties of the global object — is a new thing introduced as of ES2015; until then, all globals were properties of the global object. As of ES2015, global-level let
, const
, and class
identifier bindings are not held on the global object, but instead on a separate declarative environment record.
环境记录和词法环境对象是用于在函数中存储局部变量的相同机制(在ES2015 +和ES5及更早版本中).
Environment records and lexical environment objects are the same mechanisms used (both in ES2015+ and in ES5 and earlier) for storing local variables within a function.
此方面的全局方面在§8.2中定义.3-SetGlobalRealmObject ,它依次引用 §8.1.2.5-NewGlobalEnvironment(G,thisValue).
The global aspect of this is defined in §8.2.3 - SetGlobalRealmObject, which in turn references §8.1.2.5 - NewGlobalEnvironment(G, thisValue).
这篇关于全局let变量存储在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!