我正在阅读来自 pragmatists 的新 ES6 特性.但是在这里你可以看到他们在那个函数中使用了一个匿名 block 。 有人可以解释一下这是什么意思。它是任何javascript对象还是什么?我们如何使用它?还请提及一些引用。
function f() {
var x = 1
let y = 2
const z = 3
{
var x = 100
let y = 200
const z = 300
console.log('x in block scope is', x)
console.log('y in block scope is', y)
console.log('z in block scope is', z)
}
console.log('x outside of block scope is', x)
console.log('y outside of block scope is', y)
console.log('z outside of block scope is', z)
}
f()
最佳答案
来自 docs :
The block statement is often called compound statement in other languages. It allows you to use multiple statements where JavaScript expects only one statement. Combining statements into blocks is a common practice in JavaScript. The opposite behavior is possible using an empty statement, where you provide no statement, although one is required.
Blocks are commonly used in association with
if...else
andfor
statements.
根据您的示例:
function f() {
const z = 3
const z = 300
console.log('z outside of block scope is', z)
}
f()
如果不使用 block 作用域,我们会得到如下错误:
SyntaxError: redeclaration of const z
还有 block 作用域:
function f() {
const z = 3
{
const z = 300
console.log('z in block scope is', z)
}
console.log('z outside of block scope is', z)
}
f()
相同的代码可以正常工作。请注意, block 范围的 const z = 300
不会抛出 SyntaxError,因为它可以在 block 中唯一声明。
关于javascript - javascript ES6 中的这个匿名 block 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61473035/