ES6 Structuring Assignment?

六眼飞鱼酱① 提交于 2019-11-30 05:00:25

The closest I've come up with is to use Object.assign and a temporary object (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"}

It's fairly simple, but it's a function call and a temporary object.


Update: Bergi points out in a comment that there's a strawman proposal (link now dead) for a := operator that will do this, and one of their first use cases is indeed the use case that primarily lead me to this question: Constructors:

// 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
      //   ^^
   }
}

So given that strawman exists, I suspect for now the assign is going to be the best I can do in ES6. The old wiki with the strawman is offline, and there's nothing about := in the proposals repo.

Some experimental stuff, building on top of your answer.

If you wanted to get a little cheeky you could emulate the assignment portion of it with a setter. Definitely not practical, but it's a fun way to see what the behaviour might look like on the outside, if maybe you could empty assign 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};

Same issues you face with your answer, actually more, but some food for thought.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!