Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

柯里化

1. 柯里化

  • 柯里化

    • Currying
    • 是一种代码技术,把 一个“多参数函数” 分解成 连续调用的多个“少参数函数”,最终返回结果
  • 例子

    function add(x, y) {
      return x + y;
    }
    
    function curryingAdd(x) {
      return function (y) {
        return x + y;
      };
    }
    
    add(1, 2);
    curryingAdd(1)(2);
    
  • 相当于把 x 暂存起来,然后再调用一次函数,跟输入的 y 做计算

  • 好处

    • 实现参数复用
      • 将部分参数先填充进去,生成新函数,供后面继续调用
    • 实现延迟执行
      • 就像 bind 一样,先绑定 this,然后再真正调用执行