高阶函数基本上意味着两两件事:
这是什么意思更高阶的功能。
// 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;
});
至于你的例子,它通过返回一个函数来演示高阶函数。它也表明了关闭的概念。
Closure正在关闭作用域变量,在本例中为输入参数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