JavaScript 踩坑

1. 对有默认值的函数柯里化后调用报错

首先实现柯里化函数

function curry(fn) {
  const len = fn.length;
  return function curred(...args) {
    if (args.length >= len) {
      return fn(...args);
    } else {
      return curred.bind(null, ...args);
    }
  };
}

调用

function show(a = 0, b, c) {
  console.info(a, b, c);
}

const next = curry(show);
next("g")("ccc")("ooo");

输出:
报错

为什么会这样?
去掉参数a的默认值就好了,查阅函数的扩展 ### 函数的 length 属性做了详细的说明:第一个参数a设置了默认值导致show.length为0,(也就是说默认值导致函数参数的长度变小了)这样传递一个参数"g"调用执行了show,show执行完返回的是undefined所以后面再调用next就报错了。所以对需要柯里化的函数尽量不要传递默认值。
image.png

评论

暂无评论