ES6 默认参数为空对象?
ES6 default argument to empty object?
我正在尝试为选项参数定义具有以下行为的构造函数:
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
.
这可能吗?
在构造函数中,使用这个:
constructor({
someOption = 'foo',
otherOption = 'bar',
aSeedOfSomeSort = Math.random(),
// ...
} = {})
在末尾加上= {}
,如果没有定义就成为入参的默认值
我正在尝试为选项参数定义具有以下行为的构造函数:
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
.
这可能吗?
在构造函数中,使用这个:
constructor({
someOption = 'foo',
otherOption = 'bar',
aSeedOfSomeSort = Math.random(),
// ...
} = {})
在末尾加上= {}
,如果没有定义就成为入参的默认值