简体   繁体   中英

ES6 destructuring whole object into this

I'm wondering if there's a way to use destructuring in order to copy all properties of an object into this without knowing the props.

class MyObject {
  constructor(data) {
    this.someFlag = true

    // How can I destructure 'data' into this.
  }
}

I've seen this answer (and some other) but they all have in common the knowledge of the properties to be copied or the usage of Object.assign . I'm wondering how to do it using simple destructuring.

No, you can't use destructuring, as that would be used in redefining this which you can't do. Either go with Object.assign :

Object.assign(this, data);

Or if you really want to use destructuring some way or another:

Object.entries(data).forEach(([k, v]) => this[k] = v);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM