Three ways to type a callback function:
1. Call by pointer
2. Call by anonymous function
3, the definition and execution at the same time
//to invoke by a pointer functionMath (num1,num2,callback) {returncallback (NUM1, num2); } functionAA (num1,num2) {returnNUM1 +num2; } functionBB (num1,num2) {returnNUM1-num2; } console.log (Math (2,1,AA));//3Console.log (Math (2,1,BB));//1 //by anonymous function calls (essentially the same as in the first way) functionMath (num1,num2,callback) {returncallback (NUM1,NUM2); } console.log (Math (2, 1,function(num1,num2) {returnNUM1 +num2; }) ); //3 //definition and execution at the same time (self-executing)(function(num) {console.log (num); } )(1);//1
the function of the callback function : You can write the tool method for external use (the argument is logically processed, and then return the result directly to the callback function is OK)
// processing the input parameter, outputting the result to the callback function for external use function Parsestr (param,callback) { var result = param + ' very handsome '; Callback (result); } Parsestr (' Xu Wenxiang ',function(result) { console.log (result); // Xu Wenxiang very handsome })
Three ways of writing callback function in JS