该“高阶函数"如何进行?事情在Javascript中有效 [英] How does this "higher-order functions" thing works in Javascript

查看:73
本文介绍了该“高阶函数"如何进行?事情在Javascript中有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Marijn Haverbeke的 Eloquent Java 一书中,有此示例在介绍高阶函数的概念时:

From the book Eloquent Javascript by Marijn Haverbeke, there is this example while introducing the concept of higher-order functions:

function greaterThan(n) {
  return function(m) { return m > n; };
}
var greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
// → true

我不太确定这是如何工作的……可能回答了我自己的问题,但这是我的看法:

I'm not quite sure how this works... probably answering my own question, but this is how I see it:

  • 首先,在此行中调用greaterThan(n),并将其值分配给greaterThan10变量:

  • First, greaterThan(n) is called in this line, assigning its value to the greaterThan10 variable:

var greaterThan10 = greaterThan(10);

  • 这使存储为greaterThan10的函数看起来像:

  • This makes the function stored as greaterThan10 looks like:

    function greaterThan(10) {
      return function(m) { return m > 10; };
    }
    

  • 然后,当您调用greaterThan10(11)时,您正在调用上面的函数,该函数转换为:

  • Then, when you call greaterThan10(11) you are calling the function above, which translates to:

    function greaterThan(10) {
      return function(11) { return 11 > 10; };
    }
    

    因此,返回True作为11 > 10的结果确实是正确的.

    Hence returning True as the result as 11 > 10 is true indeed.

    有人可以确认我是否正确吗?另外,如果有人可以提供有关此高阶函数如何在JavaScript中工作的更多详细信息和评论,将不胜感激.

    Could someone confirm whether I'm correct or not? Also, if someone can provide further details and comments on how this higher-order functions work in JavaScript, that would be greatly appreciated.

    推荐答案

    从正确的角度来看,您是正确的,但对它的评估略有不同.

    You're correct, from a level of understanding, but it's evaluated slightly differently.

    var greaterThan10 = greaterThan(10);
    

    此行不会使存储为greaterThan10的函数看起来像任何东西-它创建了一个新函数,将变量n传递给它,因此greaterThan10变成了一个看起来像<的函数/p>

    This line doesn't make the function stored as greaterThan10 "look like" anything - it creates a new function, passing in the variable n to it, so that greaterThan10 becomes a function that looks like

    var greaterThan10 = function(m) { return m > 10; };
    

    当您调用它时,您是在直接调用此函数,而不再需要遍历原始函数.

    When you call it, you are calling this function directly, not going through the original function at all anymore.

    这篇关于该“高阶函数"如何进行?事情在Javascript中有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆