During the learning and interview, I was asked what higher-order functions were, but I always thought they were higher-order components. Then I introduced HOC (in fact, I was not good at it). Finally, they told me that the React map method was equivalent to a higher-order function, so I hurried down to learn higher-order functions. Of course, function corrification is also need to learn, some beginners even function corrification is what meaning do not know, I also just understand
1. Higher-order functions
A higher-order function is a function that has a function in its input argument, or a function in its output.
Function as argument
If you’ve used setTimeout, setInterval, ajax requests, then you’ve already used higher-order functions, and this is the scenario we see most often: callback functions, because they pass functions as arguments to another function.
In Ajax requests, for example, we often use callback functions to define the operation logic when the request succeeds or fails:
$. Ajax ("/url", function(result){console.log(" request successful! )})Copy the code
There are many ways to manipulate the prototype of the base object, and you can accept callback functions to easily manipulate the object. Here’s a common array.prototype.filter () method that returns a newly created Array containing all elements that return true or true after the callback function is executed.
let arr = ['a', 'aa', 'aaa', 'aaaaaaa', 'bbbbbbb', 'ccccccc']; Let result = arr.filter(function(arr) {return arr.length > 6}) // output: ["aaaaaaa", "BBBBBBB "," CCCCCCC "]Copy the code
Function as the return value
Another common scenario for higher-order functions is to print another function inside a function, such as:
function foo() {
return function bar() {}
}
Copy the code
The main use of closures is to preserve scope:
function fn() {
let num = 0
return function(a) {
return num = num + a
}
}
let adder = fn()
adder(1) //1
adder(2) //3
Copy the code
2. Coriolization of functions
Currying, as I think of it now, is a partial evaluation, that is, a code that fixes some parameters and then modifies the rest of the parameters.
Cremation has three functions:
- Parameters of reuse
- Return early
- Delayed calculation/running
Without further ado, get right to the code
function fn3 (fn, ... rest1) { return function (... rest2) { return fn.apply(null, rest1.concat(rest2)) } } function fn (name, age, Fruit) {console.log(' ${name}, ${age}, ${age})} let fn1 = fn3(fn, 'dog ') fn1(22,' Sse ') // output: Let fn2 = fn3(fn, 'Sledge hammer ', 20) Fn2 (' Tianjin ') // Output: My name is Sledge hammer, I am 22 years old, I go to school in TianjinCopy the code
The above is what I know, and what I learned today, I hope to help you, thank you. I’ll keep going