且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-13 15:43:58

执行此操作的方法有多种.第一个仅使用解构,并且将选项的属性分配给 this 上的属性:

There are multiple ways of doing this. The first one uses destructuring only and 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引擎可能会将 {...} 误认为是对象文字或块语句.

The extra parentheses are needed, otherwise the JS engine might mistake the { ... } for an object literal or a block statement.

第二个使用 Object.assign 和销毁:

The second one uses Object.assign and destructuring:

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

如果要将选项 all 应用于实例,则可以使用 Object.assign 而不进行破坏:

If you want to apply all your options to the instance, you could use Object.assign without destructuring:

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