es6如何使用非默认参数之前的默认参数? [英] 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?
下面的来自Redux.js 的示例,默认值 {}
为状态
参数有用吗? (因为你不能默认下一个参数)?
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
}
}
推荐答案
有关使用情况特定于 redux.js
。第一个参数的默认值在函数调用中通常是无用的,因为没有默认的第二个参数。
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将以第一个
时间的未定义状态调用我们的reducer。这是我们返回我们应用程序初始状态的机会:
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
}
所以这里没有真正省略第一个参数。 Redux在初始化时提供 undefined
作为其值。只有在这种情况下,教程使用默认参数语法作为快捷方式:
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
}
这篇关于es6如何使用非默认参数之前的默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!