是否可以在 JavaScript 构造函数中解构 instance/member 变量?

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

是否可以在 JavaScript class' 构造函数中使用解构赋值来为实例变量赋值,类似于对普通变量的赋值方式?

以下示例有效:

var options = {one: 1, two: 2};
var {one, two} = options;
console.log(one) //=> 1
console.log(two) //=> 2

但是我无法使类似下面的东西工作:

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

有多种方法可以做到这一点。第一个仅使用解构 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
  }
}

需要额外的括号,否则 JS 引擎可能会将 { ... } 误认为是对象字面量或块语句。

第二个使用Object.assign和解构:

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

如果您想将所有选项应用到实例,您可以使用Object.assign而不解构:

class Foo {
  constructor(options) {
    Object.assign(this, options);
  }
}

除了 Nils 的回答。它也适用于 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 用于进一步处理的自定义设置器

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}