普通函数和返回多个函数的函数之间的区别
Difference between plain function and function returning multiple functions
我不明白下面两种说法的区别。为什么在记录器中两次返回一个函数会使它变得不同?
RETURN 函数
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
}
不要 RETURN 功能
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
}
这样您就可以部分地将参数应用于函数。例如,您可能只知道(或在范围内)您在特定时间点的 store
和 next
函数。稍后,在执行过程中,您可能会有 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);
我不明白下面两种说法的区别。为什么在记录器中两次返回一个函数会使它变得不同?
RETURN 函数
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
}
不要 RETURN 功能
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
}
这样您就可以部分地将参数应用于函数。例如,您可能只知道(或在范围内)您在特定时间点的 store
和 next
函数。稍后,在执行过程中,您可能会有 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);