Is it possible to destroy instance / member variables in a JavaScript constructor?

Is it possible to use the destructuring assignment in the constructor of a JavaScript class to assign instance variables similar to how you can do this with regular 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 can't 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 
+7
javascript variable-assignment destructuring
source share
1 answer

There are several ways to do this. The first uses only destructuring, and assigns properties to properties of this properties :

 class Foo { constructor(options) { ({one: this.one, two: this.two} = options); // Do something else with the other options here } } 

Additional brackets are needed, otherwise the JS mechanism may mistakenly accept { ... } for an object literal or block statement.

The second uses Object.assign and destroys:

 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 parameters to an instance, you can use Object.assign without Object.assign :

 class Foo { constructor(options) { Object.assign(this, options); } } 
+7
source share

All Articles