ES6 结构分配?

ES6 Structuring Assignment?

ES6 are fairly well known now (live copy 在 Babel 的 REPL 上的新解构赋值特性);对于已经存在的变量:

let a, b;                 // Existing variables
let o = {a: "a", b: "b"}; // An object to get values from
// ...
({a, b} = o);             // Set them to the props from `o`
console.log(a);           // "a"
console.log(b);           // "b"

ES6 中有简单的对话吗?根据同名变量在 现有 对象上设置属性? (明显的 o.a = a; o.b = b; 除外)

注意我不是在谈论什么时候创建一个对象,我们可以使用美妙的新对象初始化语法来做到这一点,它让我们不会不必要地重复名称:

let a = "a";
let b = "b";
let o = {a, b};

但是如果我已经有一个对象,我可以在 ES6 中做一些结构化赋值吗?

我想到的最接近的方法是使用 Object.assign 和一个临时对象 (live copy):

let a = "a", b = "b";             // The variables
let obj = {c: "c"};               // The existing object
Object.assign(obj, {a, b});       // "Structuring" assignment, sort of
console.log(JSON.stringify(obj)); // "{"c":"c","a":"a","b":"b"}

这很简单,但它是一个函数调用和一个临时对象。


更新: Bergi points out that there's a strawman proposal (link 现在死了) for a := 运算符将执行此操作,他们的第一个用例确实是主要将我引向这个问题的用例:构造函数:

// From strawman proposal linked above, doesn't actually exist yet!
class Point {
   constructor(x,y) {
      this := {x,y}  //define and initialize x and y properties of new object
      //   ^^
   }
}

所以考虑到稻草人存在,我怀疑现在 assign 将是我在 ES6 中能做的最好的。 稻草人的旧 wiki 已离线,没有任何内容关于 :=proposals repo.

一些实验性的东西,建立在你的答案之上。

如果你想变得有点厚颜无耻,你可以用 setter 来模拟它的赋值部分。绝对不实用,但这是一种有趣的方式来查看行为 可能 在外部看起来像什么,如果你可以空分配 o[] =。 (Babel)

let a = '1', b = '2';
let o = {z: '26'};

Object.defineProperty(Object.prototype, '', {
  set: function (o) {
    Object.assign(this, o);
  }, configurable: true
});

o[''] = {a, b};

与您的回答所面临的问题相同,实际上更多,但值得深思。