Callback functions are very important in JavaScript and they are almost ubiquitous. Like other more traditional programming languages, there is a callback function concept, but it is very strange that there are few online tutorials to talk about the callback function, but there is a bunch of call () and apply () functions, or some short examples of using callback.
Functions are also objects
To figure out the callback function, you first have a clear understanding of the rules of the function. In JavaScript, the function is rather strange, but it is indeed an object. To be precise, a function object is created with a function () constructor. The function object contains a string that contains the JavaScript code for the functions. If you're transferring from C or Java, it might seem odd how the code might be a string. But for JavaScript, this is common. The difference between the data and the code is very vague.
You can create the function var fn = new function ("Arg1", "arg2", "return arg1 * ARG2;"); FN (2, 3); 6
One benefit of 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).
Transfer function as callback
It is easy to pass a function as a parameter.
It might seem like a bit of a hassle, maybe even a little silly, why not return the results normally? But when it comes to the need to use a 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 that is structured as 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 finish 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 the callback function is used for processing, the code can proceed with other tasks without having to wait. In practice, asynchronous calls are often used in JavaScript, and even here it is highly recommended!
The following is a more comprehensive example of using AJAX to load an XML file, and using the call () function to invoke a callback function in the context of the request object (requested objects).
function fn (URL, callback) {var HttpRequest; Create xhr HttpRequest = window. XMLHttpRequest? New XMLHttpRequest ()://Function detection window for IE. ActiveXObject? New ActiveXObject ("Microsoft.XMLHTTP"): undefined; Httprequest.onreadystatechange = function () { if (httprequest.readystate = = = 4 && Httprequest.status = = = 200 {//State judgment Callback.call (httprequest.responsexml);
We request asynchronous processing, which means that when we start the request, we tell them to call our function when it's done. In fact, the onReadyStateChange event handler also takes into account 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 Async 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 executes until the request is complete.
The above example is not easy to understand, so take a look at the following example:
function foo () {var a = ten; return function () { a *= 2; return A; };} var f = foo (); F (); return 20.f (); Return 40.
function is called externally, the variable a can still be accessed. This is because the scopes in JavaScript are lexical in nature. Functions run in the scope in which they are defined (within the scope of Foo inside the example above), not in 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 preserved, only the function that is returned can access the saved scope. Returning an inline anonymous function is the most common means of creating closures.
What is a callback?
See Wiki's Callback_ (computer_programming) Entry:
In computer programming, a callback are a reference to a piece of executable code that's passed as an argument to other CO De.
jquery document how jquery works#callback_and_functio ... Entry:
A callback is a function so is passed as an argument to another function and are executed after it parent function has C ompleted. The special thing about a callback was that functions that appear after the "parent" can execute before the callback Execut Es. Another important thing to know is what to properly pass the callback. This is where I have often forgotten the proper syntax.
Encyclopedia: Callback function
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.
Therefore, callbacks are essentially a design pattern, and the design principles of jquery (including other frameworks) follow this pattern.
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.
So callback is not necessarily used for asynchrony, and callbacks are often used in scenarios where general synchronization (blocking) is required, such as executing a callback function after certain operations have been performed.
Example
An example of using callbacks in a synchronous (blocking) purpose is to execute FUNC2 after the FUNC1 code execution is complete.
var func1=function (callback) { //do something. (Callback && typeof (callback) = = = "function") && callback ();} Func1 (FUNC2); var func2=function () {}
Examples of asynchronous callbacks:
$ (document). Ready (callback); $.ajax ({url: "test.html", context:document.body}). Done (function () {$ (the). AddClass ("Done");}). Fail (function () {alert ("error");}). Always (function () {alert (' Complete ');}); * * Note that the AJAX request is really asynchronous, but the request is made by the browser to open a new thread request, and when the state of the request changes, if the callback was previously set, the asynchronous thread generates a state change event to wait for processing on the JavaScript engine's processing queue. */
When is the callback executed?
Callback functions, which are typically executed in a synchronous context, may not be executed in an asynchronous context because the event is not triggered or the condition is not satisfied.
Use of callback functions
Resource loading: Execute callback after dynamically loading JS file, execute callback after loading IFRAME, Ajax operation Callback, image loading complete execution callback, Ajax and so on.
DOM events and node. JS events are based on a callback mechanism (the node. JS callback may have multiple layers of callback nesting issues).
SetTimeout delay Time is 0, this hack is often used, settimeout call function is actually a callback embodiment
Chained invocation: When chaining calls, it is easy to implement chained calls in the evaluator (setter) method (or in a method that does not have a return value in itself), and the accessor (getter) is relatively bad for chaining calls because you need the accessor to return the data you need instead of the this pointer. If you want to implement a chained method, you can use a callback function to implement SetTimeout, SetInterval function call to get its return value. Since all two functions are asynchronous, that is, their call timing and the program's main process is relatively independent, so there is no way to wait for their return value in the body, they are opened when the program will not stop waiting, otherwise it will lose the meaning of settimeout and setinterval, So with return there is no point, only using callback. The meaning of callback is to notify the agent function of the result of the timer execution to deal with it in time.
Delivery of callback functions
It says that you want to pass a function reference or function expression as a parameter.
$.get (' myhtmlpage.html ', mycallback);//This is the right $.get (' myhtmlpage.html ', Mycallback (' foo ', ' Bar '));//This is wrong, so take parameters? $.get (' myhtmlpage.html ', function () {/////with parameters using the expression mycallback (' foo ', ' Bar ');});
In addition, it is best to ensure that the callback exists and must be a function reference or function expression:
(Callback && typeof (callback) = = = "function") && callback ();
Understanding and using a callback function in JavaScript-2