gpt4 book ai didi

javascript - 这就是暂时死区的工作原理吗?

转载 作者:数据小太阳 更新时间:2023-10-29 05:37:20 25 4
gpt4 key购买 nike

我一直在试图弄清楚 letconst 的时间死区/解析是如何工作的。这似乎可以归结为(基于文档和我在之前的问题中收到的各种回复 [例如 thisthis ],尽管这与一些存在分歧的答案背道而驰)。这个总结正确吗?

在范围的顶部,JS引擎在相关范围的顶部创建一个绑定(bind)(变量关键字和名称的关联,例如,let foo;),这被认为提升变量,但如果您尝试在其声明位置之前访问变量,JS 会抛出 ReferenceError

一旦 JS 引擎向下移动到声明(与“定义”同义),例如 let foo;,引擎就会对其进行初始化(为其分配内存并使其可访问)。该声明具有 self 约束力。 (这是对我来说没有意义的部分:绑定(bind)导致顶部提升,但引擎在到达声明之前不会初始化,这也具有绑定(bind)效果。)如果没有赋值,在 let 的情况下,变量的值设置为 undefined,或者,如果使用 const,则 SyntaxError 将被抛出。

作为引用,以下是规范说明:

ECMAScript 2019 语言规范草案:第 13.3.1 节,Let and Const Declarations

let and const declarations define variables that are scoped to the running execution context's LexicalEnvironment. The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated. A variable defined by a LexicalBinding with an Initializer is assigned the value of its Initializer's AssignmentExpression when the LexicalBinding is evaluated, not when the variable is created. If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.

MDN 网络文档:Let

let bindings are created at the top of the (block) scope containing the declaration, commonly referred to as "hoisting". Unlike variables declared with var, which will start with the value undefined, let variables are not initialized until their definition is evaluated. Accessing the variable before the initialization results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the initialization is processed.

最佳答案

也许首先您需要了解 TDZ 存在的原因:因为它可以防止变量提升的常见意外行为并修复潜在的错误来源。例如:

var foo = 'bar';

(function () {
console.log(foo);
var foo = 'baz';
})();

这常常令许多(新手)程序员感到惊讶。 It's too late to change the behaviour of var now ,因此 ECMAScript 小组决定至少通过引入 letconst 来修复该行为。它到底是如何在引擎盖下实现的,这是一个有争议的问题,重要的是它阻止了它最有可能出现的拼写错误/结构错误:

let foo = 'bar';

(function () {
console.log(foo);
let foo = 'baz';
})();

实际上,Javascript 是分两步执行的:

  1. 将代码解析为 AST/可执行字节代码。
  2. 运行时执行。

解析器将在第一步中看到 var/let/const 声明,并将设置具有保留符号名称等的范围。那就是吊装。在第二步中,代码将在该设置范围内运行。很明显,解析器/引擎在第一步中可以自由地做任何它想做的事情,它所做的其中一件事是在内部标记 TDZ,这将在运行时引发错误。

关于javascript - 这就是暂时死区的工作原理吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50902217/

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