【问题标题】:ES6 default argument to empty object? [duplicate]ES6默认参数为空对象? [复制]
【发布时间】:2016-12-21 06:04:18
【问题描述】:

我正在尝试为选项参数定义具有以下行为的构造函数:

class Test {
  constructor({
    someOption = 'foo',
    otherOption = 'bar',
    aSeedOfSomeSort = Math.random(),
    // ...
  }) {
    console.log(
      someOption, otherOption, aSeedOfSomeSort
    );
  }
}

new Test({someOption: 'lol'});
new Test({otherOption: 'derp'});
new Test({aSeedOfSomeSort: 0.5});
new Test({});
new Test(); // here's the problem

这很好用,但是,我希望构造函数能够工作,以便使用所有默认参数,我不必传递空对象。我不在乎对象本身是否在参数中命名,但在构造函数的上下文中,我想要一种干净的方式来直接访问所有选项而无需命名空间或使用with

这可能吗?

【问题讨论】:

  • 感谢 Oriol!没看到

标签: javascript constructor ecmascript-6 default-value


【解决方案1】:

在构造函数中,使用这个:

constructor({
  someOption = 'foo',
  otherOption = 'bar',
  aSeedOfSomeSort = Math.random(),
  // ...
} = {})

通过在末尾添加= {},如果未定义则成为输入参数的默认值。

Example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 2019-07-23
    • 2016-10-30
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    相关资源
    最近更新 更多