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
JavaScript Object Destructuring is the syntax for extracting values from an object property and assigning them to a variable. The destructuring is also possible for JavaScript Arrays.
Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. That is, we can extract data from arrays and objects and assign them to variables.
Nested Object and Array Destructuring Here's another example with an array of objects: You can destructure as deeply as you like: As you can see, keys a , b , and c are not implicitly defined, even though we pulled out nested values, firstElemOfC and remainingElementsOfC , from the array at c .
There are multiple ways of doing this. The first one uses destructuring only and assigns the properties of options to properties on this
:
class Foo { constructor(options) { ({one: this.one, two: this.two} = options); // Do something else with the other options here } }
The extra parentheses are needed, otherwise the JS engine might mistake the { ... }
for an object literal or a block statement.
The second one uses Object.assign
and destructuring:
class Foo { constructor(options) { const {one, two} = options; Object.assign(this, {one, two}); // Do something else with the other options here } }
If you want to apply all your options to the instance, you could use Object.assign
without destructuring:
class Foo { constructor(options) { Object.assign(this, options); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With