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

后端 未结 2 527
-上瘾入骨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:09

    In addition to Nils´s answer. It also works with object spread (...)

    class Foo {
    
      constructor(options = {}) {
        ({
          one: this.one,
          two: this.two,
          ...this.rest
        } = options);
      }
    }
    
    let foo = new Foo({one: 1,two: 2,three: 3,four: 4});
    
    console.log(foo.one);  // 1
    console.log(foo.two);  // 2
    console.log(foo.rest); // {three: 3, four: 4}

    ... and/or custom settters for further processing

    class Foo {
    
        constructor(options = {}) {
            ({
                one: this.one,
                two: this.two,
                ...this.rest
            } = options);
        }
       
        set rest(options = {}) {
            ({
              three: this.three,
              ...this.more
            } = options);
        }
    }
    
    let foo = new Foo({one: 1,two: 2,three: 3,four: 4});
    
    console.log(foo.one);   // 1
    console.log(foo.two);   // 2
    console.log(foo.three); // 3
    console.log(foo.more);  // {four: 4}

提交回复
热议问题