代码之家  ›  专栏  ›  技术社区  ›  Aran Freel

普通函数与返回多个函数的函数的区别

  •  0
  • Aran Freel  · 技术社区  · 8 年前

    我不理解下面两种说法之间的区别。为什么在记录器中返回两次函数会有什么不同?

    返回函数

    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 回复  |  直到 5 年前
        1
  •  2
  •   dashton    8 年前

    这样您就可以部分地将参数应用于函数。例如,您可能只知道(或在范围内) store next 在特定时间点运行。之后,在执行过程中,你可能会 action 参数,但 百货商店 超出范围。

    因此,您可以部分应用前两个参数,然后传递返回的函数,以便在稍后的阶段最终可以使用第三个参数执行它。当最后使用第三个参数执行时,它可以访问前两个参数,因为它们包含在部分应用的函数中。举例说明:

     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);