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

[亡魂溺海] 提交于 2019-12-05 05:55:16

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
}

The defaults are called when the parameter is undefined:

todo(undefined, { type: 'WHATEVER' });

To prevent the need for setting undefineds when calling the function, I prefer to destructure an object with defaults. Using an object make the order of the params irrelevant.

todo({ state = {}, action } = {}) => {};

Default parameter has to come last i dont think there is a direct way to make them come before other parameters however you can use Arguments Object to achieve something like this.

e.g

function myFunction(){
  var firstParam , secondParam;
  if(arguments.length === 0){
     console.log("no input");
     return;
  }
  if(arguments.length === 1){
    secondParam =  arguments[0];
  }
  else{
    firstParam  =  arguments[0];
    secondParam =  arguments[1];
  }
   // you can write any logic above
   // also you can give params in function definition as well myFunction(firstParam , secondParam)
   // use params as you wish
  console.log(firstParam);
  console.log(secondParam);
}

I'm a newbe to javascript but if I am not mistaken, default parameters simply replace 'undefined' parameters.

if I have a function defined as:

function example(var1 = false, var2, var3 = false) ...

This means that the following calls are all legal :

example(true, someVar, true);
example(true, someVar); // calls  example(true, someVar, false)
example(undefined, someVar, true); // calls example(false, someVar, true)
example(undefined, someVar); // calls example(false, someVar, true)

The redux framework simply passed undefined explicitly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!