Definition: In JavaScript, the callback function is specifically defined as: function A is passed as a parameter (function reference) to another function B, and this function B executes function A. Let's just say that function A is called a callback function. If there is no Name (function expression), it is called an anonymous callback function.
Understanding: A callback function is a function that is called through a function pointer. If you pass the pointer (address) of the function as an argument to another function, when the pointer is used to invoke the function it points to, we say this is a callback function. The callback function is not called directly by the implementing party of the function, but is invoked by another party when a particular event or condition occurs, and is used to respond to the event or condition.
As an example:
//first, create a generic poem's generating function, which will act as the callback function for the following getuserinput function functionGenericpoemmaker (name, gender) {Console.log (name+ "is finer than fine wine."); Console.log ("Altruistic and noble for the modern time."); Console.log ("Always admirably adorned with the latest style."); Console.log ("A" + gender + "of unfortunate tragedies who still manages A perpetual smile"); } //callback, the last item of the parameter, will be the Genericpoemmaker function we defined above functiongetuserinput (FirstName, LastName, Gender, callback) {varFullName = FirstName + "" +LastName; //Make sure the callback is a function if(typeofcallback = = = "function") { //Execute The callback function and pass the parameters to itCallback (FullName, gender); }} getuserinput ("Michael", "Fassbender", "Man", Genericpoemmaker); //Output/* Michael Fassbender is finer than fine wine. Altruistic and noble for the modern time. Always admirably adorned with the latest style. A man of unfortunate tragedies who still manages a perpetual smile. */
We can change a callback function to try:
functiongreetuser (customerName, sex) {varSalutation = sex && sex = = = "Man"? "Mr.": "Ms."; Console.log ("Hello," + Salutation + "" +customerName);} //use GreetUser as a callback functionGetuserinput ("Bill", "Gates", "Man", GreetUser); //here is the outputHello, Mr Bill Gates.
The understanding and application of JS callback function