Understanding and usage of callback functions in js
1. The role of callback functions
js code will be executed from top to bottom, but sometimes we need to wait until one operation is completed before proceeding to the next operation. At this time You need to use the callback function.
2. Explanation of callback function
Because a function is actually a kind of object, it can be stored in a variable, passed to another function through parameters, created inside the function, and the result value is returned from the function" because the function is Built-in objects, we can pass it as a parameter to another function, execute it in the function, and even return it after execution. It has always been regarded as a difficult technology by "professional programmers"
Callback function. The English explanation is:
A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.
The translation is: a callback function is a function that is passed as a variable to another function , it is executed after the main function is executed.
function A has a parameter function B, and function B will be called and executed after function A is executed.
3. How to use the callback function
The code is as follows:
function a(callbackFunction){ alert("这是parent函数a"); var m =1; var n=3; return callbackFunction(m,n); } function b(m,n){ alert("这是回调函数B"); return m+n; } $(function(){ var result = a(b); alert("result = "+ result); });
The execution order is:
This is parent function a
This is callback function B
result = 4
The function first executes theme function a, then calls callback function b, and finally returns the return value of function a.