In JavaScript, the callback function is specifically defined as: function A is passed to another function B as an argument (a function reference), and this function B executes function A. Let's just say 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 in asynchronous, general synchronization (blocking) scenarios are often used in the callback, such as the requirement to perform some operations after the callback function.
Example
An example of using callbacks in a synchronization (blocking) to execute FUNC2 after func1 code execution completes.
var func1=function (callback) {
Do something.
(Callback && typeof (callback) = = "function") && callback ();
}
Func1 (FUNC2);
var func2=function () {
}
Use of callback functions
Resource loading: Dynamically loading JS files after the callback, loading the IFRAME to perform the callback, Ajax operation callback, picture loading complete execution callback, Ajax and so on.
DOM events and Node.js events are based on a callback mechanism (a Node.js callback may have problems with multi-tier callback nesting).
SetTimeout delay Time is 0, this hack is often used, settimeout called function is actually a callback embodiment
Chained call: When chained call, it is easy to implement chained calls in the assignment (setter) method (or in a method that does not have a return value in itself), and the accessor (getter) is relatively difficult to implement chained calls, because you need to return the data you need instead of the this pointer. If you want to implement a chained method, you can use the callback function to implement the
The settimeout, setinterval function call gets its return value. Since two functions are asynchronous, that is: their call time sequence and the main process of the program is relatively independent, so there is no way to wait for their return value in the main body, they are opened when the program will not stop to wait, otherwise it will lose the meaning of settimeout and setinterval, So using return has no meaning, only use callback. The significance of the callback is to notify the agent function of the result of the timer execution to be processed in time.
function is also an object
To figure out the callback function, first clearly understand the rules of the function. In JavaScript, a function is rather strange, but it is indeed an object. Rather, a function is an object created with a function () constructor. The function object contains a string containing the JavaScript code for the functions. If you turn from C or Java, it may seem strange, how can the code be a string? But for JavaScript, this is normal. The difference between the data and the code is very vague.
You can create a function like this
var fn = new Function ("Arg1", "arg2", "return arg1 * ARG2;");
FN (2, 3); 6
One advantage of doing this is that you can pass code to other functions, or you can pass a regular variable or object (because the code is literally just an object).
Pass function as callback
It's 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 Results
}
FN (A, function (num) {
Console.log ("Callback called! NUM: "+ num);
})//The random number between 10 and 20
It might seem like a bit of a hassle, even a little silly, and why did you return the results abnormally? But when you have to use the callback function, you may not think so!
Get out of the way
The traditional function enters data as a parameter and returns a value using the return statement. Theoretically, there is a return statement at the end of the function, structurally: an input point and an output point. It is easier to understand that a function is essentially a mapping of the implementation process between input and output.
However, when the implementation of the function is very long, do you choose to wait for the function to complete processing, or use the callback function for asynchronous processing? In this case, it becomes critical to use a callback function, such as an AJAX request. If you use a callback function for processing, the code can continue to perform other tasks without having to wait. In actual development, asynchronous calls are often used in JavaScript, and are even strongly recommended here!
Here's a more comprehensive example of using AJAX to load an XML file and using the call () function to invoke the callback function in the context of the request object (requested object).
function fn (URL, callback) {
var HttpRequest; Create XHR
HttpRequest = window. XMLHttpRequest? New XMLHttpRequest ():
Window. ActiveXObject? New ActiveXObject ("Microsoft.XMLHTTP"): undefined;//for IE for functional detection
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 functions
Console.log (this); Output after this statement
});
Console.log ("This'll run before the above callback."); This statement first outputs
We request asynchronous processing, which means that when we start the request, we tell them to call our functions when they are done. In practice, the onReadyStateChange event handler also has to consider the failure of the request, where we assume that the XML file exists and can be successfully loaded by the browser. In this example, the asynchronous function is assigned to the onReadyStateChange event, so it is not executed immediately.
Finally, the second Console.log statement executes first because the callback function does not execute until the request completes.
The above example is not easy to understand, so 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.
function is called externally, you can still access variable A. This is because the scopes in JavaScript are lexical in nature. Functions run in the scope that defines them (the scope within Foo in the example above) rather than the scope in which this function is run. As long as f is defined in Foo, it can access all the variables defined in Foo, even if the execution of Foo is finished. Because its scope is saved, it is only the returned function that can access the saved scope. Returning an inline anonymous function is the most common means of creating closures.