Callback function definition
A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.
demo
Take the definition of one function as an argument to another function.
function fn(param, callback){
callback(param)
}
fn('XiaoMing'.function f(param){
console.log('Hello ' + param);
})
Copy the code
Callback functions in JavaScript have been described above. Readers may feel ridiculous, because the above description can be described as correct nonsense.
We know it from zero
A callback function is still a function calling function in nature, and a callback function is called as an argument to another function.
The usual way to call a function
function f1(){
return 1;
}
function f2(){
return f1();
}
Copy the code
The above code shows calling function f1 from function F2.
We rarely write such a function in production practice, because F2 is “mechanical” in calling F1 and only returns 1 in a step-by-step manner. We actually need to determine the return value based on the user’s data. So let’s transform the function this way.
function f1(param){
return 1 + param;
}
function f2(param){
return f1(param);
}
Copy the code
The above function returns a value incremented by one based on user input.
In this way, the program has the flexibility to expand the scope of application on the basis of the previous, according to the user’s input, output different values.
But even so, can it adapt to our actual production? The processing of the above function is fixed, as shown below:
If we have a requirement that the user input an array of integers, we need to sort it using a different algorithm. Then we have two ways to handle it:
In approach one we consider the complete process for each process, but in Approach two we only require that the operation be extensible.
Above we converted fixed output to flexible output by setting parameters. Next we also convert fixed to flexible processing by setting parameters. That’s why callbacks exist.
function f2(param, callback){
return callback(param);
}
// call f2 with f1 as the parameter, so our operation is flexible.
f2(2.function f1(param){
return param + 1;
})
Copy the code
The above code is the application of the callback function, increasing the extensibility of the program.