gpt4 book ai didi

javascript - 为什么 `const arg = arg;` 会产生 "Cannot access before initialization"错误?

转载 作者:行者123 更新时间:2023-12-03 08:13:12 24 4
gpt4 key购买 nike

我发现了我以前从未想过的非常奇怪的行为。我不确定这是否与 TDZ 有关,因为我认为 TDZ 是从外部作用域到内部作用域,而不是像本例那样相反。请注意下面示例中的 arg

// Works

const test = {
func: (arg) => {
const obj = {
foo: arg,
}
return obj.foo;
}
}
// Error

const test = arg => {
{
const arg = arg; // Cannot access 'arg' before initialization
}
}

最佳答案

出现错误消息的原因是 letconst 声明都是 block-scoped ,这意味着它们只能在它们周围的{ }内访问。因此,由于 constlet,如果另一个 变量 (arg) 则不会访问外部作用域的 变量 (arg) 在 block 作用域内被定义。

或者换句话说:括号大括号内的变量argarg不同code> 您传递给函数是因为您在内部使用了 letconst

在解析 block 作用域时,引擎已经为内部定义的每个变量保留了名称。但它们只能在使用 const 或 let 声明和求值之后才能访问。

因此,在写入时读取它会导致您看到的错误。

var variable;
{ // [block/env start]
let variable = variable; // ReferenceError: Cannot access 'variable' before initialization
} // [block/env end]

letvariable=variable期间发生的情况是,它必须先读取右侧,然后再将值/引用分配给左侧,但根据定义,该变量在声明之前不可用,因此它会抛出错误。

另一个例子是:

var variable;
{
console.log(variable); // ReferenceError: Cannot access 'variable' before initialization
let variable;
}

执行顺序与示例中的赋值类似,并引发相同的错误。它不会访问外部变量,因为另一个变量是使用let/const在该 block 作用域内定义的。

您还可以查看 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 Environment Record 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.

关于javascript - 为什么 `const arg = arg;` 会产生 "Cannot access before initialization"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70254629/

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