ES6 - 默认参数与解构相结合:此模式的含义是什么?

时间:2016-09-19 06:38:44

标签: 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,
        cancelLabel: cancelLabel,
        submitLabel: submitLabel
    });
},

完整的帖子: https://codereview.stackexchange.com/questions/141699/react-modal-visibility-and-content-toggling-based-on-action-clicked

我想说这是ES6默认参数和破坏的组合。

试图了解目的。但还是不知道。

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

任何人都可以解释一下这种模式的含义吗?

1 个答案:

答案 0 :(得分:3)

  

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

在JavaScript中我们称之为"参数,"不是参数,但是,是的,那是什么。它有三个部分。让我们逐个构建它:

  1. 解构。在函数中,我们希望将titledescription等用作本地,因此我们声明了解构参数:

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

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

    // Add in a default for the object as a whole
    toggleModal({title = null, description = null, cancelLabel = 'No', submitLabel = 'Yes'} = {}) {
    // ------------------------------------------------------------------------------------^^^^^
    
  4. 所以这个:

    toggleModal();
    
    例如,没有争论,做同样的事情:

    toggleModal({});
    

    ...因为总体默认值(上面的#3)开始了,这与此相同:

    toggleModal({title: null, description: null, cancelLabel: 'No', submitLabel: 'Yes'});
    

    ...因为个人默认值(上面的#2)开始了。

    因为参数是解构的,所以函数可以在体内使用titledescription等(上面的#1)。

    这是一个更简单的例子:

    
    
    // REQUIRES ES2015+ SUPPORT IN YOUR BROWSER
    function adams({answer = 42, question = "Life, the Universe, and Everything"} = {}) {
      console.log("Answer: " + answer);
      console.log("Question: " + question);
    }
    
    adams();
    console.log("--");
    adams({answer: 67});
    console.log("--");
    adams({question: "The mice are revolting!"});
    console.log("--");
    adams({
      question: "Would you like a piece of cake?",
      answer: "Yes, please!"
    });
    
    
    

    输出:

    Answer: 42
    Question: Life, the Universe, and Everything
    --
    Answer: 67
    Question: Life, the Universe, and Everything
    --
    Answer: 42
    Question: The mice are revolting!
    --
    Answer: Yes, please!
    Question: Would you like a piece of cake?