有人可以帮助我理解这个事件处理程序的结构吗?为什么它们有两个排列的箭头功能?
const callAll = (...fns) => (...args) => fns.forEach(fn => fn && fn(...args));
最佳答案
它是一个高阶函数——一个返回另一个函数的函数。在这种特殊情况下,当给定函数列表时,您的函数将返回一个新函数,该函数依次将这些函数应用到其参数。这个高阶函数通常称为 compose
或 pipe
,因为这就是它的作用 - 通过一系列函数运行参数,就像 unix 管道一样(你知道,就像grep | sort | uniq
)
请注意,您的示例并不是特别惯用,更好的编写方式是
pipe = (...fns) => x => fns.reduce((x, f) => f(x), x)
可以像这样使用
pipe = (...fns) => x => fns.reduce((x, f) => f(x), x)
upper = s => s.toUpperCase()
reverse = s => [...s].reverse().join('')
bang = s => s + '!'
convert = pipe(reverse, upper, bang)
result = convert('hello')
console.log(result)
关于javascript - 为什么这个事件处理程序有两个箭头函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53603208/