`var {...} = ...`语句中的花括号是做什么的? [英] What does curly brackets in the `var { ... } = ...` statements do?
问题描述
不确定这是否是特定于Mozilla的JS语法,但我经常发现变量以这种方式声明,例如,在附加SDK文档:
Not sure if this is a Mozilla-specific JS syntax, but I often found variables being declared this way, for example, in add-on SDK docs:
var { Hotkey } = require("sdk/hotkeys");
以及各种chrome Javascript( let
声明用于代替 var
),
and in various chrome Javascript (let
statement is being used in place of var
),
let { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
我发现它很混乱,但我无法找到任何关于这两种语法的文档,即使是 MDN 。
I found it very confusing but I am not being able to find any documentation about both syntax, even on MDN.
推荐答案
它们都是JavaScript 1.7的功能。第一个是 块级变量 :
They're both JavaScript 1.7 features. The first one is block-level variables:
让
允许你声明变量,限制其范围到使用它的块,语句或表达式。这与var
关键字不同,后者无论块范围如何,都在全局或本地定义一个变量。
let
allows you to declare variables, limiting its scope to the block, statement, or expression on which it is used. This is unlike thevar
keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
第二个被称为 解构 :
The second one is called destructuring:
解构分配可以使用数组或对象提取数据反映数组和对象文字构造的语法。
...
使用解构赋值可以做的一件特别有用的事情是在单个语句中读取整个结构,虽然你可以用它们做很多有趣的事情,如下面的例子中所示。
Destructuring assignment makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
...
One particularly useful thing you can do with destructuring assignment is to read an entire structure in a single statement, although there are a number of interesting things you can do with them, as shown in the section full of examples that follows.
对于那些熟悉Python,它类似于这种语法:
For those familiar with Python, it's similar to this syntax:
>>> a, (b, c) = (1, (2, 3))
>>> a, b, c
(1, 2, 3)
第一个代码块是简写:
var {Hotkey: Hotkey} = require("sdk/hotkeys");
// Or
var Hotkey = require("sdk/hotkeys").Hotkey;
您可以将第二个代码块重写为:
You can rewrite the second code chunk as:
let Cc = Components.classes;
let Ci = Components.interfaces;
let Cr = Components.results;
let Cu = Components.utils;
这篇关于`var {...} = ...`语句中的花括号是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!