gpt4 book ai didi

javascript - 为什么 Const 能够在其 block 作用域之外被调用?

转载 作者:行者123 更新时间:2023-12-03 00:00:29 26 4
gpt4 key购买 nike

为什么在下面的实例中允许调用const。

const pizza = {

topping1: "ham",
topping2: "pepperoni"

}

console.log(pizza.topping2);

从技术上讲,“pizza.topping2”位于大括号之外。那么为什么它有效呢?我认为你必须以某种方式调用 const,但是,关于 const 的类(class),说明它仅用作 block 级变量。这可能看起来像一个新手问题(确实如此),但对我来说理解编写语法背后的逻辑很重要。

最佳答案

在当前示例中,花括号 {} 并未创建 block 作用域。它只是用作 Object initializer

Objects can be initialized using new Object(), Object.create(), or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).

根据MDN

A block statement (or compound statement in other languages) is used to group zero or more statements. The block is delimited by a pair of curly brackets and may optionally be labelled

语法:

{
StatementList
}

以下代码片段将引发错误

{
const x = 3;
}
console.log(x)

关于javascript - 为什么 Const 能够在其 block 作用域之外被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55197602/

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