是否可以在JavaScript构造函数中构造实例/成员变量?

时间:2016-06-30 15:23:43

标签: javascript variable-assignment destructuring

是否可以在JavaScript类的构造函数中使用解构赋值来分配类似于如何对常规变量执行的实例变量?

以下示例有效:

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

2 个答案:

答案 0 :(得分:21)

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

答案 1 :(得分:0)

除了尼尔斯的答案。它也可以与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}

...和/或自定义setter以便进一步处理

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}

相关问题