1. Callback function definition
A callback function is a function called through a function pointer. If you pass the pointer (address) of the function as an argument to another function, when this pointer is used to call the function it points to, we say this is a callback function. The callback function is not called directly by the implementer of the function, but is called by another party when a specific event or condition occurs, and is used to respond to the event or condition.
In JavaScript, the specific definition of the callback function is: function A is passed as a parameter (function reference) into another function B, and this function B executes function A. Let's say that function A is called a callback function. If there is no name (function expression), it is called an anonymous callback function. Therefore, callback is not necessarily used for asynchronousness. Callbacks are often used in general synchronous (blocking) scenarios, such as requiring some operations to be executed and the callback function is executed.
example
An example of using callbacks in synchronization (blocking) is to execute func2 after the func1 code is executed.
var func1=function(callback){ //do something. (callback && typeof(callback) === "function") && callback();}func1(func2); var func2=function(){}2. Use occasions of callback function
Resource loading: Execute callback after dynamic loading of js files, execute callback after loading iframe, execute callback after loading ajax operation callback, execute callback after image loading, AJAX, etc.
DOM events and Node.js events are based on callback mechanism (Node.js callbacks may have multi-layer callback nesting problems).
The delay time of setTimeout is 0. This hack is often used. The function called by setTimeout is actually a callback embodiment
Chain call: When chain call, it is easy to implement chain call in the evaluator (setter) method (or in methods that do not return values), but the value getter is relatively difficult to implement chain call, because you need the value getter to return the data you need instead of this pointer. If you want to implement chain method, you can use a callback function to implement it.
The function calls of setTimeout and setInterval get their return value. Since both functions are asynchronous, that is, their call timing and the main process of the program are relatively independent, there is no way to wait for their return value in the body, and the program will not stop and wait when they are opened, otherwise the meaning of setTimeout and setInterval will be lost. Therefore, it is meaningless to use return, so callback can only be used. The meaning of callback is to notify the proxy function of the timer execution results for timely processing.
3. Functions are also objects
If you want to understand the callback function, you must first clearly understand the rules of the function. In JavaScript, functions are strange, but they are indeed objects. To be precise, a function is a Function object created with the Function() constructor. The Function object contains a string containing the javascript code of the function. If you were transferred from C or java, this might seem strange, how could the code be a string? But for javascript, this is pretty common. The difference between data and code is vague.
//The function can be created in this way var fn = new Function("arg1", "arg2", "return arg1 * arg2;");fn(2, 3); //6One advantage of this is that you can pass code to other functions, or you can pass regular variables or objects (because the code is literally just an object).
Transfer function as callback
It is easy to pass a function as a parameter.
function fn(arg1, arg2, callback){ var num = Math.ceil(Math.random() * (arg1 - arg2) + arg2); callback(num);//pass the result}fn(10, 20, function(num){ console.log("Callback called! Num: " + num); });//The result is a random number between 10 and 20Maybe doing this seems cumbersome and even a bit stupid, why not return the result abnormally? But when you have to use a callback function, you may not think so!
Don't get in the way
Traditional functions enter data as parameters and use return statements to return values. In theory, there is a return return statement at the end of the function, which is structured: an input point and an output point. This is easier to understand. Functions are essentially mapping the implementation process between input and output.
However, when the implementation process of the function is very long, should you choose to wait for the function to complete processing, or use the callback function to perform asynchronous processing? In this case, using callback functions becomes critical, such as: AJAX request. If you use a callback function for processing, the code can continue to perform other tasks without emptying it. In actual development, asynchronous calls are often used in javascript, and it is even highly recommended here!
Below is a more comprehensive example of loading XML files using AJAX, and using the call() function to call the callback function in the context of the requested object.
function fn(url, callback){ var httpRequest; //Create XHR httpRequest = window.XMLHttpRequest ? new XMLHttpRequest() : window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP" ) : undefined;//Functional detection for IE httpRequest.onreadystatechange = function(){ if(httpRequest.readystate === 4 && httpRequest.status === 200){ //Status judgment callback.call(httpRequest.responseXML); } }; httpRequest.open("GET", url); httpRequest.send();}fn("text.xml", function(){ //Call the function console.log(this); //Output after this statement}); console.log("this will run before the above callback."); //This statement outputs firstOur requests for asynchronous processing means that when we start requesting, we tell them to call our function when they are finished. In actual situations, the onreadystatechange event handler must also consider the request failure. Here we assume that the xml file exists and can be loaded successfully by the browser. In this example, the asynchronous function is assigned to the onreadystatechange event and is therefore not executed immediately.
Finally, the second console.log statement is executed first, because the callback function is not executed until the request is completed.
The above example is not easy to understand, so take a look at the following example:
function foo(){ var a = 10; return function(){ a *= 2; return a; }; }var f = foo();f(); //return 20.f(); //return 40.The function is called externally and can still access the variable a. This is all because the scope in javascript is lexical. Functional runs in the scope that defines them (the scope inside foo in the example above), rather than in the scope where this function is run. As long as f is defined in foo, it can access all variables defined in foo, even if the execution of foo has ended. Because its scope will be saved, but only the returned function can access the saved scope. Returning an embedded anonymous function is the most common method to create closures.
The above is all about this article, I hope it will be helpful for everyone to learn JavaScript programming.