在JavaScript构造函数中,是否可能对实例/成员变量进行解构赋值?

36

在 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
我认为更一般的问题是是否有一种解构赋值形式,可以在现有对象上创建属性,而不是在对象初始化器上创建。 - Pointy
1
无论如何,总是有Object.assign(this, options); - Pointy
1
值得一提的是,您也可以在构造函数之外应用相同的语法。给出两个对象:let o = {a: 1, b: 2}, p = {};。将 o 解构为一个更简单的 p 非常容易:({b: p.b} = o);p 产生了 Object {b: 2} - user6445533
这个回答解决了你的问题吗?不使用var的对象解构 - user202729
2个回答

66
有多种方法可以做到这一点。第一种只使用解构,将选项的属性分配给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
谢谢@nils!这正是我在寻找的。第一种解决方案最为简明,使用了稍微更高级的析构方式,你可能已经知道或者在阅读/运行代码时很快就会想到。第二种方法最清晰、最明显,而第三种方法非常适合你所描述的用例。 - Aaron

3
除了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}

...还可以使用自定义的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}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接