javascript - javascript ES6 中的这个匿名 block 是什么?

标签 javascript ecmascript-6 block

我正在阅读来自 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 and for 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/

相关文章:

javascript - 在我的设计 html/css/javascript 中需要帮助

javascript - range.setStart 仅使用字符偏移量?

javascript - 切换纵向-横向-纵向后丢失媒体查询匹配

javascript - 在 1.5 中访问组件 $scope inside 指令

css - 自定义初始页面上的奇怪 float /宽度问题(动态调整大小)(

objective-c - 在 iOS 4 中使用 Block Completion Handler 制作动画

javascript - 用字符串填充数组的最佳方法

javascript - 如果 0 为 null,则更改数组中每个对象的值

javascript - StandardJs + ES6 扩展类 - 无用的构造函数?

c++ - 如何在删除期间摆脱虚假的 _BLOCK_TYPE_IS_VALID 断言失败?