What is a callback function in JS?

First of all, we must understand one thing, what are formal parameters and actual parameters?

We all know that functions can accept parameters, formal parameters and actual parameters.

function num(A,B){
    return A+B;
}
num(1,2)

I believe you have seen countless examples of this on countless websites, calculating the sum of two numbers, but it does not affect its classic simplicity.

Then when you define this function, A and B are the formal parameters, and 1 and 2 are the actual parameters. Parameters can be used or not. Formal parameters, formal parameters, have no practical meaning, but are set to help you complete the internal logic operations of the function.

Callback function : A function that is passed into another function as an actual parameter and called in the external function to complete certain tasks is called a callback function.

function greeting(name){
    alert('Hello' + name);
}
function fun(callback){
    var name = prompt('请输入你的名字')
    callback(name);
}
fun(greeting);

A function A, as a parameter of another function B, then function A is called a callback function.

Callback function A is an ordinary function, which is called by other function B as a parameter inside B, then A can be called the callback function of B at this time.

The concept of callback function is mutual. A single function cannot be called a callback function, it can only be called a callback function of XXX (who is called internally). I believe most people are confused here. Let's take another chestnut.

Guess you like

Origin blog.csdn.net/wsdshdhdhd/article/details/126678892