I would like to deconstruct an object similar to this
const {header, content} = this.data
where data has
data: {header: 'some header', content: 'some content'}
to a class attribute so I can call
this.header
or this.content
anywhere in the class.
I was assuming it would be something like this
{this.header, this.content} = this.data
or
this {header, content} = this.data
but both throw errors.
Is it even possible to deconstruct assign directly to class properties?
You can do it with destructuring, because the target of a destructuring assignment can be just about anything you can assign to, but it doesn't really buy you much:
({header : this.header, content: this.content} = data);
(Parens are only needed so the {
doesn't look like the start of a block.)
Live Example:
class Example { constructor(data) { ({header : this.header, content: this.content} = data); console.log(this.header); console.log(this.content); } } new Example({header: 'some header', content: 'some content'});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.