Is it possible to use destructuring assignment in a JavaScript class' constructor to assign the instance variables similar to how you can do it to normal variables?
The following example works:
var options = {one: 1, two: 2};
var {one, two} = options;
console.log(one) //=> 1
console.log(two) //=> 2
But I cannot get something like the following to work:
class Foo {
constructor(options) {
{this.one, this.two} = options;
// This doesn't parse correctly and wrapping in parentheses doesn't help
}
}
var foo = new Foo({one: 1, two: 2});
console.log(foo.one) //=> I want this to output 1
console.log(foo.two) //=> I want this to output 2
Object.assign(this, options);
– Mattresslet o = {a: 1, b: 2}, p = {};
. Deconstructo
to a less complexp
is a peace of cake:({b: p.b} = o);
yieldsObject {b: 2}
forp
. – Kokoschka