最近我在研究 Firefox Add-on Builder SDK 来源,并偶然发现了这样的常量声明:
const { getCodeForKey, toJSON } = require("../../keyboard/utils");
我可以找到关于 CommonJS Modules 的信息, 但是这个作业的左边部分让我有点困惑,因为它必须是特定于语言的,而且我无法在谷歌上搜索任何内容。
谁能给我指点一些说明这里发生了什么的规范/草案?
最佳答案
这是一个 destructuring assignment ,目前仅由 Firefox 使用的 SpiderMonkey JavaScript 引擎实现。以下是它如何处理数组:
// Destructuring assignment
[a, b] = foo;
// Equivalent code
a = foo[0];
b = foo[1];
下面是它如何处理对象:
// Destructuring assignment
{a, b} = foo;
// Equivalent code
a = foo.a;
b = foo.b;
一个稍微复杂一点的例子:
// Destructuring assignment
{name: a, address: {line1: b}} = foo;
// Equivalent code
a = foo.name;
b = foo.address.line1;
因此您的代码示例等同于:
var utilsExports = require("../../keyboard/utils");
const getCodeForKey = utilsExports.getCodeForKey;
const toJSON = utilsExports.toJSON;
这只是一种更方便的编写方式。
关于javascript - 带 block 的常量声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10199229/