普通函数和返回多个函数的函数之间的区别

时间:2018-01-20 21:43:38

标签: javascript reactjs redux middleware

我不明白下面两个陈述之间的区别。为什么在记录器中返回两次函数使它有所不同?

返回功能

const logger = store => next => action => {
    let result
    console.groupCollapsed("dispatching", action.type)
    console.log('prev state', store.getState())
    console.log('action', action)
    result = next(action)
    console.log('next state', store.getState())
    console.groupEnd()
    return result
}

不返回功能

const logger = (store, next, action) => {
    let result
    console.groupCollapsed("dispatching", action.type)
    console.log('prev state', store.getState())
    console.log('action', action)
    result = next(action)
    console.log('next state', store.getState())
    console.groupEnd()
    return result
}

1 个答案:

答案 0 :(得分:2)

这样您可以将参数部分应用于该功能。例如,您可能只知道(或具有范围)您在特定时间点的storenext函数。稍后,在执行期间,您可能会拥有action参数,但store超出范围。

因此,您可以部分应用前两个参数,然后传递返回的函数,以便最后使用第三个参数执行它。当最后使用第三个参数执行它时,它可以访问前两个参数,因为它们被包含在部分应用的函数中。一个例子可能会澄清:

 const store = {
    getState: () => 'foo'
}
// this can be passed around, it creates a closure around store so will have access to it later
const partialLogger = logger(store)((ac) => ({
    ac,
    bar: 2
}));
// some time later - execute
const res = partialLogger({ type: 'baz' });
console.log('>res', res);
相关问题