联系:中间件挂载原理。

    1. // 聚合函数,查看 redux 源码
    2. function fn1 (x) {
    3. console.log('fn1', x)
    4. return x
    5. }
    6. function fn2 (x) {
    7. console.log('fn2', x)
    8. return x
    9. }
    10. function fn3 (x) {
    11. console.log('fn3', x)
    12. return x
    13. }
    14. // 聚合函数
    15. function compose(...funcs) {
    16. // 防止 compose 函数,入参为空
    17. if (!funcs.length) return arg => arg
    18. // compose 函数,入参只有一个参数,立即执行
    19. if (funcs.length === 1) return funcs[0]
    20. // args 是 a 函数传入的参数
    21. // 主要传入函数的执行顺序,a , b 可相互在其内部执行:a(b(...args)) 或 b(a(...args))
    22. return funcs.reduce((a, b) => (...args) => a(b(...args)))
    23. }
    24. // var a = compose()('msg')
    25. // a // msg
    26. var a = compose(fn1, fn2, fn3)('msg')
    27. a // fn3 msg ; fn2 msg ; fn1 msg ; msg
    1. function fn1 (x) {
    2. return x + 1;
    3. }
    4. function fn2 (x) {
    5. return x + 2;
    6. }
    7. function fn3 (x) {
    8. return x + 3
    9. }
    10. function fn4 (x) {
    11. return x + 4
    12. }
    13. // 要求:var a = compose(fn1, fn2, fn3, fn4)
    14. // console.log(a(1)) // 1+4+3+2+1=11
    15. var a = compose(fn1, fn2, fn3, fn4)(1)
    16. a // 11