T.J*_*der 13 javascript destructuring variable-assignment ecmascript-6
ES6的新解构分配功能现在已经众所周知(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"
Run Code Online (Sandbox Code Playgroud)
ES6中是否有简单的说法?基于具有相同名称的变量设置现有对象的属性?(除了显而易见的o.a = a; o.b = b;)
注意我不是在讨论创建对象时,我们可以使用美妙的新对象初始化器语法来实现这一点,这样我们就不会不必要地重复这些名称:
let a = "a";
let b = "b";
let o = {a, b};
Run Code Online (Sandbox Code Playgroud)
但是如果我已经有了一个对象,我可以在ES6中进行某种结构分配吗?
T.J*_*der 10
我最接近的是使用Object.assign和临时对象(实时复制):
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"}
Run Code Online (Sandbox Code Playgroud)
这很简单,但它是一个函数调用和一个临时对象.
更新: BERGI指出在评论这有一个稻草人提案 (链接现在死了)的:=运营商,将做到这一点,他们的第一个使用案例之一确实使用情况下,主要导致我这个问题:构造函数:
// 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
// ^^
}
}
Run Code Online (Sandbox Code Playgroud)
因此,鉴于稻草人存在,我怀疑现在这老维基与稻草人处于脱机状态,并没有什么关于assign将是我在ES6中能做的最好的事情.:=在提议回购.