2014-09-30 53 views
1

我正在阅读Eloquent Javascript第5章。他们给出了下面这个令我困惑的例子。了解Javascript中的高阶函数

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

任何人都可以尽可能简单地分解给我。我在回调方面遇到了很大的麻烦。特别是当涉及到这些情况时。

回答

7

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

  • 功能可以采取其它功能参数/输入
  • 功能可以回报功能

这是什么意思更高阶的功能。

// 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 
6

这里没有涉及“回调”。 “greaterThan”函数的功能是返回另一个函数的函数。

所以,你调用函数:

var greaterThan10 = greaterThan(10); 

现在变量“greaterThan10”引用与10作为参数调用“大于”函数返回的功能。

然后,您登录调用该函数的结果:

console.log(greaterThan10(11)); 

功能从“大于”返回被调用。它将其参数与创建时传递的参数“n”的值进行比较。由于11实际上大于10,因此该函数将返回true,这就是要记录的内容。