了解Javascript中的高阶函数 [英] Understanding Higher Order functions in Javascript

查看:72
本文介绍了了解Javascript中的高阶函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在阅读Eloquent Javascript第5章。他们给出了以下示例,这使我感到困惑。

I am currently reading Eloquent Javascript Chapter 5. They give the following example which is confusing the hell out of me.

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

任何人都可以尽可能简单地将其分解为我。我在回调方面遇到了很大的麻烦。

Can anyone break this down to me as simply as possible. I have huge trouble with callbacks. Especially when it comes to situations like these.

推荐答案

高阶函数基本上意味着两件事:

Higher-Order functions basically mean two things:


  • 函数可以将其他函数用作参数/输入

  • 函数可以返回函数

  • Functions can take other functions as an argument/input
  • Functions can return functions

这就是高阶函数的意思。

This is what is meant by higher-order functions.

// this function takes a function as an argument
function myFunc(anotherFunc) {
  // executes and returns its result as the output which happens to be a function (myFunc)
  return anotherFunc();
}

// let's call myFunc with an anonymous function
myFunc(function() { 
 // this returns a function as you see
 return myFunc;
});

如您的示例所示,它通过返回一个函数来演示高阶函数。它还显示了闭包的概念。

As for your example, it demonstrates higher-order functions by returning a function. It also demonstrates the notion of closure.

闭包正在对作用域变量(在本例中为输入参数n)进行闭包。

Closure is closing over a scoped variable, in this case the input argument n.

function greaterThan(n) {
  // n is closed over (embedded into and accessible within) the function returned below
  return function(m) { return m > n; };
}

// greatherThan10 reference points to the function returned by the greaterThan function
// with n set to 10
// Notice how greaterThan10 can reference the n variable and no-one else can
// this is a closure
var greaterThan10 = greaterThan(10);

console.log(greaterThan10(11));
// → true

这篇关于了解Javascript中的高阶函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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