`var { ... } = ...` 语句中的大括号有什么作用? [英] What does curly brackets in the `var { ... } = ...` statements do?

查看:39
本文介绍了`var { ... } = ...` 语句中的大括号有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定这是否是 Mozilla 特定的 JS 语法,但我经常发现以这种方式声明的变量,例如,在 附加 SDK 文档:

var { Hotkey } = require("sdk/hotkeys");

以及在各种 chrome Javascript 中(使用 let 语句代替 var),

let { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;

我发现它非常令人困惑,但我无法找到有关这两种语法的任何文档,即使在 MDN.

解决方案

它们都是 JavaScript 1.7 的特性.第一个是块级变量:

<块引用>

let 允许您声明变量,将其范围限制为使用它的块、语句或表达式.这与 var 关键字不同,它定义了一个全局变量,或者是整个函数的局部变量,而不考虑块的作用域.

第二个叫做解构:

<块引用>

解构赋值可以使用反映数组和对象字面量构造的语法从数组或对象中提取数据.
...
您可以使用解构赋值做的一项特别有用的事情是在单个语句中读取整个结构,尽管您可以使用它们做许多有趣的事情,如下面的完整示例部分所示.

对于熟悉 Python 的人来说,它类似于以下语法:

<预><代码>>>>a, (b, c) = (1, (2, 3))>>>甲、乙、丙(1, 2, 3)

第一个代码块是:

var {Hotkey: Hotkey} = require("sdk/hotkeys");//或者var Hotkey = require("sdk/hotkeys").Hotkey;

您可以将第二个代码块重写为:

let Cc = Components.classes;让 Ci = Components.interfaces;让 Cr = Components.results;让 Cu = Components.utils;

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");

and in various chrome Javascript (let statement is being used in place of var),

let { classes: Cc, interfaces: Ci, results: Cr, utils: Cu }  = Components;

I found it very confusing but I am not being able to find any documentation about both syntax, even on MDN.

解决方案

They're both JavaScript 1.7 features. The first one is block-level variables:

let allows you to declare variables, limiting its scope to the block, statement, or expression on which it is used. This is unlike the var 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.

For those familiar with Python, it's similar to this syntax:

>>> a, (b, c) = (1, (2, 3))
>>> a, b, c
(1, 2, 3)

The first code chunk is shorthand for:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆