Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

javascript - es6 how to use default parameters that go before non-default parameters?

I am a bit rusty on default parameters, and I am wondering how can I use a default value for a parameter if it goes before parameters without defaults?

In the example from Redux.js below, when will the default value {} for the state parameter be useful? (since you can't default the next parameter)?

const todo = (state = {}, action) => {
  switch (action.type) {
    //...

    case 'TOGGLE_TODO':
      if (state.id !== action.id) {
        return state
      }

      return Object.assign({}, state, {
        completed: !state.completed
      })

    default:
      return state
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The usage in question is specific to redux.js. The default value for the first parameter is generally useless in function calls because of the second parameter without default.

However, as said earlier in the same tutorial about Reducers:

Redux will call our reducer with an undefined state for the first time. This is our chance to return the initial state of our app:

function todoApp(state, action) {
  if (typeof state === 'undefined') {
    return initialState
  }
  //...
  return state
}

So the 1st parameter isn't really omitted here. Redux is supplying undefined as its value on initialization. It is only in this case, the tutorial used default arguments syntax as a shortcut:

function todoApp(state = initialState, action) {
  //...
  return state
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...