发布于 2026-01-06 0 阅读
0

函数式编程基础(第二部分):高阶函数

函数式编程基础(第二部分):高阶函数

那么,什么构成最高阶函数呢?

要被称作函数Higher order function,要么必须接受另一个函数作为参数,要么必须返回一个函数。

把函数作为参数???什么?不可能吧!!

让我们先来编写一个简单的非最高阶函数:

const addYtoX = (x, y) => x + y
Enter fullscreen mode Exit fullscreen mode

现在我们尝试将此函数传递给另一个函数:

const ofTheHighestOrder = (f, x, y) =>  f(x, y)

console.log (ofTheHighestOrder(addYtoX, 1, 2)) // 3
Enter fullscreen mode Exit fullscreen mode

哇,成功了!!正如你所见,我们可以将函数传递给其他函数,并像使用其他属性一样使用它们!

让我们重新称呼一下殿下,让它更具权威性:

    const performOperation = (operation, x, y) =>  operation(x, y)

    console.log (performOperation(addYtoX, 1, 2)) // 3
Enter fullscreen mode Exit fullscreen mode

这样说得通吧?我希望你现在能明白高阶函数的价值和潜力吧?

我们来看另一个例子:

    const addYtoX = (x, y) => x + y
    const multiplyYbyX = (x, y) => x * y
    const performOperation = (operation, x, y) =>  operation(x, y)

    console.log (performOperation(addYtoX, 1, 2)) // 3
    console.log (performOperation(multiplyYbyX, 1, 2)) // 2
Enter fullscreen mode Exit fullscreen mode

瞧!我们还可以做更多的事情,但现在我们先到此为止,来看看高阶函数的第二种变体;一个返回函数的函数……嗯,听起来很奇怪,让我们写一个看看它是否有效!

    const ofTheHighestOrder = () => {
        return poke = () => '... your highness?? '
    }

    console.log(ofTheHighestOrder()) // function poke()
Enter fullscreen mode Exit fullscreen mode

太棒了!正如你所见,我们能够从一个函数中返回另一个函数!!!让我们再深入研究一下这个函数:

    const ofTheHighestOrder = () => {
        return poke = () => '... your highness?? '
    }

    const willPoke = ofTheHighestOrder()

    console.log(willPoke()) // ... your highness?? 
Enter fullscreen mode Exit fullscreen mode

太棒了!我们可以使用返回函数的函数来创建其他函数,这使得它们也成为最高阶函数。

现在看来这似乎没什么用,但这为更多可能性打开了大门,我们将在后续剧集中探讨这些可能性。

在此之前,保持高昂的斗志!

文章来源:https://dev.to/ysael/function-programming-basics-part-2-higher-order-function-2ckl