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

标签 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

最佳答案

有多种方法可以做到这一点。第一个仅使用解构和 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 引擎可能会将 { ... } 误认为是对象字面量或 block 语句。

第二个使用 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);
  }
}

关于javascript - 是否可以在 JavaScript 构造函数中解构实例/成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38127416/

相关文章:

variables - 重新分配接口(interface)或允许 GC 对临时变量进行处理

javascript - typescript 对象解构结果为 "Property assignment expected."

javascript - 将数组解构为对象

javascript - JS Closure 编译器,用于数组解构的@param 语法?

javascript - Codility "PermMissingElem"Javascript 解决方案

javascript - 当子节点未全部选中时取消选中父节点

javascript - d3js svg 水滴或泪滴

javascript - 在两个 div 之间滚动自动调整 div

c++ - 双类型赋值错误,C++

scala - Scala 中的赋值方法