简体   繁体   English

为什么在 JavaScript 中的 window object 中添加了全局变量?

[英]Why are global variables added to a window object in JavaScript?

Why are global variables added to a window object in JavaScript?为什么在 JavaScript 中的 window object 中添加了全局变量?

var a = 1;
console.log(window.a);

ECMAScript 2015 language specification does not say that declared var or function is added to window global objects. ECMAScript 2015 语言规范没有说声明的 var 或 function 被添加到 window 全局对象中。 However, I would like to know why the global variable declared var is added as a property to the window object.但是,我想知道为什么将声明为 var 的全局变量作为属性添加到 window object 中。

What I'm curious about is that it has nothing to do with ECMAScript language specification?我很好奇的是它与 ECMAScript 语言规范无关?

I used a translator, so please understand if it's weird.我使用了翻译器,所以如果它很奇怪,请理解。

It actually is noted in the specification here , when a variable is assigned to when no such identifier exists:实际上,在此处的规范中已指出,当不存在此类标识符时将变量分配给:

If IsUnresolvableReference(V) is true, then
  a. If V.[[Strict]] is true, throw a ReferenceError 
exception.
  b. Let globalObj be GetGlobalObject().
  c. Return ? Set(globalObj, V.[[ReferencedName]], W, false).

And here , in CreateGlobalVarBinding, which is called when a variable is declared at the top level of a script .在这里,在 CreateGlobalVarBinding 中,当在脚本的顶层声明变量时调用它。

6. Let varDeclarations be the VarScopedDeclarations of script.
...
18. For each String vn of declaredVarNames, do
  a. Perform ? env.CreateGlobalVarBinding(vn, false).

The global object may be the window in a browser, or self in a web worker, or the Node global , etc.全局 object 可能是浏览器中的window ,或者是 web worker 中的self ,或者Node global等。

I think the reason why var causes properties to be added to the global object (in the example you provided) has to do with how environments are linked in Javascript;我认为var导致属性被添加到全局 object (在您提供的示例中)的原因与 Javascript 中环境的linked方式有关; they are linked by outer references , yet the global environment has no outer reference.它们由外部引用链接,但全局环境没有外部引用。 Perhaps the choice to bind them to the global object, as properties, stems from this lack of outer reference in the global environment.也许将它们绑定到全局 object 作为属性的选择源于全局环境中缺乏外部引用。

The global scope is the “outermost” scope – it has no outer scope.全局 scope 是“最外层”的 scope - 它没有外层 scope。 Its environment is the global environment.它的环境是全球环境。 Every environment is connected with the global environment via a chain of environments that are linked by outer references.每个环境都通过由外部引用链接的环境链与全局环境连接。 The outer reference of the global environment is null .全局环境的外部参考是null

Source: https://2ality.com/2019/07/global-scope.html#the-global-object来源: https://2ality.com/2019/07/global-scope.html#the-global-object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM