关于upperCase返回withUpperCase函数及调用逻辑的技术问询
问题解答
1. 为什么upperCase函数会返回withUpperCase函数?
upperCase是一个高阶函数(即返回函数的函数),它用了柯里化的箭头函数写法:
const upperCase = (...fns) => firstItem => fns.reduce((acc, currentValue) => currentValue(acc), firstItem)
当你调用upperCase(toUpperCase, toExtend, toRepeat)时,它会先接收传入的三个函数参数,然后返回一个新的函数(就是定义里的firstItem => ...部分),这个返回的函数就是被赋值给withUpperCase的内容。
2. 表达式const withUpperCase = upperCase(...)的含义
完全正确,就是把upperCase(...)的返回值(一个函数)赋值给withUpperCase,让withUpperCase变成一个可以接收字符串参数的函数。
这里upperCase的参数是三个字符串处理函数,upperCase会把这些函数“打包”起来,返回的新函数在后续被调用时,会按顺序执行这些打包好的函数。
3. 调用withUpperCase(' I love coding')的具体工作机制
当调用这个函数并传入目标字符串时,会按以下步骤执行:
- 传入的字符串
' I love coding'作为初始值,被赋值给reduce方法的累加器acc。 reduce开始遍历之前传入upperCase的三个函数,依次执行:- 第一步:用
acc(初始字符串)调用toUpperCase,得到' I LOVE CODING',这个结果成为新的acc。 - 第二步:用更新后的
acc调用toExtend,得到' I LOVE CODING!',再次更新acc。 - 第三步:用最新的
acc调用toRepeat,得到' I LOVE CODING! I LOVE CODING! I LOVE CODING!'。
- 第一步:用
- 最后
reduce返回最终的acc,也就是第三步的结果,最终被console.log输出。
完整代码回顾
const toUpperCase = (string) => string.toUpperCase(); const toExtend = (string) => `${string}!`; const toRepeat = (string) => string.repeat(3); const upperCase = (...fns) => firstItem => fns.reduce((acc, currentValue) => currentValue(acc), firstItem) const withUpperCase = upperCase( toUpperCase, toExtend, toRepeat ); console.log(withUpperCase(' I love coding')); // 输出:" I LOVE CODING! I LOVE CODING! I LOVE CODING!"
内容的提问来源于stack exchange,提问作者user20977536
相关产品推荐
相关产品推荐

