本文介绍了让语句在全局对象上创建属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JavaScript 中,var 声明在全局对象上创建属性:

In JavaScript, var declarations create properties on the global object:

var x = 15;
console.log(window.x); // logs 15 in browser
console.log(global.x); // logs 15 in Node.js

ES6 通过 let 具有块作用域的声明.

ES6 introduces lexical scoping with let declarations that have block scope.

let x = 15;
{
   let x = 14;
}
console.log(x); // logs 15;

但是,这些声明是否会在全局对象上创建属性?

However, do these declarations create properties on the global object?

let x = 15;
// what is this supposed to log in the browser according to ES6?
console.log(window.x); // 15 in Firefox
console.log(global.x); // undefined in Node.js with flag

推荐答案

根据规范,否:

一个全局环境记录在逻辑上是一个单一的记录,但它被指定为一个复合封装对象环境记录声明性环境记录.对象环境记录作为其基础object 关联的 Realm 的全局对象.这个全局对象是全局环境记录的GetThisBinding具体方法返回的值.全局环境记录的对象环境记录组件包含所有内置全局变量的绑定(第 18 条) 以及全局代码中包含的 FunctionDeclarationGeneratorDeclarationVariableStatement 引入的所有绑定.全局代码中所有其他 ECMAScript 声明的绑定包含在 声明性环境记录 全局环境记录的组成部分.

更多解释:

  • 声明性环境记录将绑定存储在内部数据结构中.以任何方式都无法掌握该数据结构(想想函数作用域).

  • A declarative environment record stores the bindings in an internal data structure. It's impossible to get a hold of that data structure in any way (think about function scope).

object 环境记录使用实际的 JS 对象作为数据结构.对象的每个属性都成为绑定,反之亦然.全局环境有一个对象环境对象,它的绑定对象"就是全局对象.另一个例子是with.

An object environment record uses an actual JS object as data structure. Every property of the object becomes a binding and vice versa. The global environment has an object environment object whose "binding object" is the global object. Another example is with.

现在,正如引用的部分所述,只有 FunctionDeclarations、GeneratorDeclarations 和 VariableStatements 在全局环境的 object 环境记录.IE.只有 this 绑定成为全局对象的属性.

Now, as the cited part states, only FunctionDeclarations, GeneratorDeclarations, and VariableStatements create bindings in the global environment's object environment record. I.e. only this bindings become properties of the global object.

所有其他声明(例如constlet)都存储在全局环境的declarative 环境记录中,该记录不基于全局对象.

All other declarations (e.g. const and let) are stored in the global environment's declarative environment record, which is not based on the global object.

这篇关于让语句在全局对象上创建属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 08:02
查看更多