2016-08-15 78 views
-1

我试图定义具有以下行为的选项参数的构造:ES6默认参数为空对象?

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的所有选项。

这可能吗?

+0

谢谢Oriol!没有看到 –

回答

0

在构造,使用:

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

通过在末处加入= {},变得如果没有定义输入参数的默认值。

Example