Where are global let variables stored? [duplicate]

一曲冷凌霜 提交于 2019-12-11 07:35:48

问题


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

Here let navigator value shadows the window.navigator. But I am very curious to know where exactly the let navigator gets stored in?


回答1:


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).

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.

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.

The global aspect of this is defined in §8.2.3 - SetGlobalRealmObject, which in turn references §8.1.2.5 - NewGlobalEnvironment(G, thisValue).



来源:https://stackoverflow.com/questions/41848022/where-are-global-let-variables-stored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!