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

后端 未结 2 524
-上瘾入骨i
-上瘾入骨i 2021-02-07 02:31

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

2条回答
  •  孤街浪徒
    2021-02-07 03:24

    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);
      }
    }
    

提交回复
热议问题