ES6结构分配? [英] ES6 Structuring Assignment?
问题描述
ES6 的新的解构任务功能现在已经很熟悉了(现场副本在Babel的REPL上);在存在的变量的情况下:
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:
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中是否有一个简单的相反?基于具有相同名称的变量,在现有对象上设置属性? (除了明显的 oa = a; ob = b;
)
Is there a simple converse in ES6? Setting properties on an existing object based on variables with the same name? (Other than the obvious o.a = a; o.b = b;
)
注意我不是在说什么创建一个对象,我们可以通过美妙的新对象初始化器语法来实现,不用重复这些名称:
Note I'm not talking about when creating an object, we could do that with the wonderful new object initializer syntax that lets us not repeat the names unnecessarily:
let a = "a";
let b = "b";
let o = {a, b};
但是如果我已经有一个对象,我可以做某种
But if I already have an object, can I do some kind of structuring assignment in ES6?
推荐答案
最近我想出的是使用 Object.assign
和一个临时对象(现场副本):
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.
更新: Bergi 指出在评论中有一个用于执行此操作的:=
操作符的草稿提案,其中第一个用例之一确实是主要使用此问题的用例:构造函数:
Update: Bergi points out in a comment that there's a strawman proposal 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
// ^^
}
}
因此,鉴于这个秸秆存在,我怀疑现在,这个分配将是我在ES6中能做的最好的。
So given that strawman exists, I suspect for now the assign
is going to be the best I can do in ES6.
这篇关于ES6结构分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!