JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

8.8.2 Higher-Order Functions

8.8.2 Higher-Order Functions

A higher-order function is a function that operates on functions, taking one or more functions as arguments and returning a new function. Here is an example:

// This higher-order function returns a new function that passes its // arguments to f and returns the logical negation of f's return value; function not(f) {

return function() { // Return a new function var result = f.apply(this, arguments); // that calls f return !result; // and negates its result.

}; }

var even = function(x) { // A function to determine if a number is even return x % 2 === 0; };

8.8 Functional Programming | 193

var odd = not(even); // A new function that does the opposite [1,1,3,5,5].every(odd); // => true: every element of the array is odd

The not() function above is a higher-order function because it takes a function argument and returns a new function. As another example, consider the mapper() function below. It takes a function argument and returns a new function that maps one array to another using that function. This function uses the map() function defined earlier, and it is important that you understand how the two functions are different:

// Return a function that expects an array argument and applies f to // each element, returning the array of return values. // Contrast this with the map() function from earlier. function mapper(f) {

return function(a) { return map(a, f); }; }

var increment = function(x) { return x+1; }; var incrementer = mapper(increment); incrementer([1,2,3]) // => [2,3,4]

Here is another, more general, example that takes two functions f and g and returns a new function that computes f(g()):

// Return a new function that computes f(g(...)). // The returned function h passes all of its arguments to g, and then passes // the return value of g to f, and then returns the return value of f. // Both f and g are invoked with the same this value as h was invoked with. function compose(f,g) {

return function() { // We use call for f because we're passing a single value and // apply for g because we're passing an array of values. return, g.apply(this, arguments));

}; }

var square = function(x) { return x*x; }; var sum = function(x,y) { return x+y; }; var squareofsum = compose(square, sum); squareofsum(2,3) // => 25

The partial()and memoize()functions defined in the sections that follow are two more important higher-order functions.

友情链接It题库(| 版权归yishouce.com所有| 友链等可联系|粤ICP备16001685号-1