2015-06-17 39 views
12

ES6的新解构赋值特征现在已经相当熟悉(Babel的REPL上的live copy);在变量的情况下已经存在:ES6构造作业?

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中?

+1

这听起来像你想让对象初始化缩写能够'扩展'现有的对象。我理解正确吗? – Mathletics

+0

@Mathletics:或者其他具有这种结果的机制,是的。 –

+0

我不明白你的问题。所以你有一个现有的对象'{a:“a”}'。你有一个变量b,其值为“b”。你想要做什么? –

回答

10

我想出最接近的是使用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指出in a commentthere's a strawman proposal:=运营商,将做到这一点,他们的第一个使用案例之一是确实使用情况下,主要导致我对这个问题:构造函数:

// 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中能做的最好的。

+1

没有什么我能想到的比这更好。在一天结束时,速记对象属性是折叠键和值的唯一方法,因此创建临时对象是必需的。 – loganfsmyth

+0

@loganfsmyth:谢谢。 ES6非常丰富,我想知道我是否错过了一些东西。我有一半希望得到一个近乎即时的答复,指出明显的东西,并感觉像一个娃娃。 :-) –

+0

这是如此接近你会得到 –

1

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

如果你想得到一个小脸蛋,你可以用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}; 

同样的问题,你面对你的答案,其实更多,但一些思考的食物。

+1

我的眼睛受伤了。不过创意。 –