Understanding Higher Order functions in Javascript

痴心易碎 提交于 2020-01-04 14:31:27

问题


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.


回答1:


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.

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



回答2:


There's no "callback" involved here. What you've got with the "greaterThan" function is a function that returns another function.

So, you call the function:

var greaterThan10 = greaterThan(10);

Now the variable "greaterThan10" references the function returned by the "greaterThan" function invoked with 10 as the argument.

Then, you log the result of calling that function:

console.log(greaterThan10(11));

The function returned from "greaterThan" is invoked. It compares its parameter to the value of the parameter "n" passed when it was created. Because 11 is in fact greater than 10, the function will return true and that's what'll be logged.



来源:https://stackoverflow.com/questions/26131645/understanding-higher-order-functions-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!