【问题标题】:Is it possible to destructure instance/member variables in a JavaScript constructor?是否可以在 JavaScript 构造函数中解构实例/成员变量?
【发布时间】:2016-11-02 19:17:09
【问题描述】:

是否可以在 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

【问题讨论】:

  • 我认为更普遍的问题是,是否有一种解构赋值形式提供在现有对象上创建属性而不是对象初始值设定项。
  • 反正总有Object.assign(this, options);
  • 值得一提的是,您也可以在构造函数之外应用相同的语法。给出了两个对象:let o = {a: 1, b: 2}, p = {};。将o 解构为不那么复杂的p 是小菜一碟:({b: p.b} = o);p 生成Object {b: 2}
  • 这能回答你的问题吗? object destructuring without var

标签: javascript variable-assignment destructuring


【解决方案1】:

有多种方法可以做到这一点。第一个只使用解构和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!这正是我一直在寻找的。第一个解决方案是最简洁的,它使用了一种稍微高级的解构,您在阅读/运行代码时已经知道或很快就知道了。第二个是最清晰和最明显的,而第三个非常适合您概述的用例。
【解决方案2】:

除了尼尔斯的回答。它也适用于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}

...和/或用于进一步处理的自定义设置器

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}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-26
    • 2012-08-21
    • 1970-01-01
    • 2011-08-08
    • 2014-01-12
    • 2023-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多