Javascript ES6-默认参数与分解相结合:这种模式意味着什么?

Javascript ES6-默认参数与分解相结合:这种模式意味着什么?,javascript,design-patterns,ecmascript-6,Javascript,Design Patterns,Ecmascript 6,我在CodeReview问题中看到了这些模式: toggleModal({title = null, description = null, cancelLabel = 'No', submitLabel = 'Yes'} = {}) { this.setState({ modalVisible: !this.state.modalVisible, title: title, description: description,

我在CodeReview问题中看到了这些模式:

toggleModal({title = null, description = null, cancelLabel = 'No', submitLabel = 'Yes'} = {}) {
    this.setState({
        modalVisible: !this.state.modalVisible,
        title: title,
        description: description,
        cancelLabel: cancelLabel,
        submitLabel: submitLabel
    });
},
全文如下:

我会说它是ES6默认参数与破坏的组合

我试着去理解目的。但还是不知道

为什么不单独使用默认参数

有人能解释一下这种模式是怎么回事吗

我会说它是ES6默认参数与解构的组合

在JavaScript中,我们称它们为参数,而不是参数,但是的,这就是它。它有三个部分。让我们一部分一部分地构建它:

破坏结构。在函数中,我们希望使用title、description等作为局部变量,因此我们声明destructuring参数:

// Just the destructuring
toggleModal({title, description, cancelLabel, submitLabel}) {
我们希望这些单独的属性具有默认值,因此我们为它们指定默认值:

// Add in defaults for the props
toggleModal({title = null, description = null, cancelLabel = 'No', submitLabel = 'Yes'}) {
// ---------------^^^^^^^-------------^^^^^^^-------------^^^^^^^-------------^^^^^^^^
我们还希望使整个对象成为可选对象,因此我们为该对象指定了一个默认值:

// Add in a default for the object as a whole
toggleModal({title = null, description = null, cancelLabel = 'No', submitLabel = 'Yes'} = {}) {
// ------------------------------------------------------------------------------------^^^^^
因此:

toggleModal();
e、 g.,无参数,做的事情与此相同:

toggleModal({});
toggleModal({title: null, description: null, cancelLabel: 'No', submitLabel: 'Yes'});
…因为上面的整体默认3起作用,这与此相同:

toggleModal({});
toggleModal({title: null, description: null, cancelLabel: 'No', submitLabel: 'Yes'});
…因为个人默认值为上面的2

因为参数是非结构化的,所以函数可以在上面的正文1中使用标题、描述等

下面是一个简单的例子:

//在您的浏览器中需要ES2015+支持 函数adams{答案=42,问题=生命、宇宙和一切}={}{ console.logAnswer:+answer; console.logQuestion:+问题; } 亚当斯; console.log-; 亚当斯{答复:67}; console.log-; 亚当斯{问题:老鼠在反抗!}; console.log-; 亚当斯{ 问题:你想要一块蛋糕吗?, 回答:是的,谢谢!
};我想我得到了:当没有任何对象被指定为具有默认属性的对象时,您可以替换整个对象。以及向“不完整对象”(缺少一个或多个参数的对象)添加默认属性。“我理解对了吗?”米泽克:我不确定我是否理解。={}部分使toggleModal在不提供任何参数的情况下工作,它为参数提供了默认值。{title=null…等提供了对象属性的默认值,并对其进行了解构。对此进行了一些修改,我已经很清楚了。:非常感谢。你让我开心。@mizech:不用担心,很高兴这有帮助。我更新了答案,试图让它更清楚。