ES6 Structuring Assignment?

前端 未结 2 528
广开言路
广开言路 2020-12-29 08:58

The new destructuring assignment features of ES6 are fairly well known now (live copy on Babel\'s REPL); in the case of variables that already exist:



        
2条回答
  •  有刺的猬
    2020-12-29 09:55

    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.

提交回复
热议问题