了解大括号“{}”的上下文

Understanding the Context of Curly Brackets '{}'

我一直在审查其他人的代码,虽然 ES2015 总体上需要一些时间来适应,但是,我仍然坚持解构。

以前,在 Javascript 中,花括号 {} 用于块或对象。例如

// Curly Brackets Block
If () {
  ...
}

// Curly Brackets in Obj
var obj = {
  a : 1,
  ...
}

然而,在解构中,我们一次又一次地看到以下语法:

let a = ({ a, b }) => {
}

我的问题是,参数容器是实际对象还是只是一个块? 请说明以下是否与上述代码相同:

let a = ( a, b ) => {
}

编辑:我从阅读 Axel Rauschmayers 关于解构的文章中了解到(到目前为止)我们只是在映射道具。总是进入一个新的对象?即:

let a = { first : a, second : b } = AnObj;
===
a.a === AnObj.first;
a.b === AnObj.second;

以上是否正确? obj 总是被实例化吗?但是,这在上面的函数中没有意义,因此为 props 创建的对象将是一个匿名对象,对吗?

非常感谢,

用于解构:

var obj = {a: 1, b: 2},
    add = ({a, b}) => a + b;

console.log(add(obj));  //3

所以基本上函数内部的语句看起来有 2 个参数,但是当你调用它时你只传递一个对象。

不,解构中的大括号既不构成块也不构成对象文字。

它们绝对不是块,因为它们不是语句(并且不包含语句列表),它们是表达式就像对象文字。事实上,它们甚至具有与对象字面量相同的语法,唯一的区别是它们位于赋值目标(赋值运算符的左侧)或函数参数的位置。

Is let a = ({ a, b }) => {…} the same as let a = ( a, b ) => {…}?

不,真的不是。两个参数列表都为函数范围声明变量 ab,但第一个函数需要一个具有属性 .a.b 的对象,而第二个函数需要两个参数。

My understanding is that we are merely mapping the properties into a new obj?

没有。没有新对象 created/instantiated。只有您传入的对象(右侧)。它被 解构 - "pulled apart" - 分成碎片,然后分配给各种子目标(变量,属性 引用)。

要写

a.b = anObj.first;
a.c = anObj.second;

使用解构赋值

({first: a.b, second: a.c}) = anObj;

(括号是区分表达式和块所必需的)。

然而,更常见的用例是用于变量初始化。你可以缩短

let b = anObj.first,
    c = anObj.second;

let {first: b, second: c} = anObj;

还有一个 shorthand 当变量与 属性 同名时,所以

let first = anObj.first,
    second = anObj.second;

等同于

let {first, second} = anObj;

Is let a = { first : a, second : b } = anObj; correct?

不,这没有多大意义。它会脱糖到

let a;
a = anObj.first;
b = anObj.second;
a = anObj;