【发布时间】: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