gpt4 book ai didi

javascript - let 语句是否在全局对象上创建属性?

转载 作者:IT王子 更新时间:2023-10-29 03:07:55 26 4
gpt4 key购买 nike

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

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

ES6 通过 let 引入词法作用域具有 block 作用域的声明。

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

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

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

最佳答案

Do let statements create properties on the global object?

根据spec , 不:

A global environment record is logically a single record but it is specified as a composite encapsulating an object environment record and a declarative environment record. The object environment record has as its base object the global object of the associated Realm. This global object is the value returned by the global environment record’s GetThisBinding concrete method. The object environment record component of a global environment record contains the bindings for all built-in globals (clause 18) and all bindings introduced by a FunctionDeclaration, GeneratorDeclaration, or VariableStatement contained in global code. The bindings for all other ECMAScript declarations in global code are contained in the declarative environment record component of the global environment record.

更多解释:

  • 声明性 环境记录将绑定(bind)存储在内部数据结构中。不可能以任何方式掌握该数据结构(考虑功能范围)。

  • 一个对象环境记录使用一个实际的JS对象作为数据结构。对象的每个属性都成为绑定(bind),反之亦然。全局环境有一个对象环境对象,其“绑定(bind)对象”是全局对象。另一个例子是with

现在,正如引用部分所述,只有 FunctionDeclarationGeneratorDeclarationVariableStatement 在全局环境的 对象环境记录。 IE。只有此绑定(bind)成为全局对象的属性。

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

关于javascript - let 语句是否在全局对象上创建属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28776079/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com