Tell you what javascript callback functions are. _ basic knowledge-js tutorial

Source: Internet
Author: User
Callback functions are very important in javascript, and they are almost ubiquitous. For example, other more traditional programming languages have the callback function concept, but it is very strange that the number of online tutorials on callback functions is relatively small, but there are a bunch of calls () and apply () function, or some short examples of callback usage. Functions are also objects

To understand the callback function, you must first understand the function rules. In javascript, functions are strange, but they are actually objects. Specifically, a Function is a Function object created by using Function. The Function object contains a string that contains the javascript code of the Function. If you switch from C or java, this may seem strange. How can the code be a string? But for javascript, this is common. The difference between data and code is vague.

// Create the Function var fn = new Function ("arg1", "arg2", "return arg1 * arg2;"); fn (2, 3); // 6

One benefit of doing so is that code can be passed to other functions, or regular variables or objects (because the code is literally just an object ).

  Passing functions 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); // transfer result} fn (10, 20, function (num) {console. log ("Callback called! Num: "+ num) ;}); // the random number between 10 and 20 is returned.

It may seem troublesome or even silly to do so. Why can't I return results normally? However, when a callback function must be used, you may not think so!

No Way Out

Traditional Functions input data as parameters and return values using return statements. Theoretically, there is a return statement at the end of the function, which is structured as an input point and an output point. This is easy to understand. A function is essentially a ing between the input and output processes.

However, when the function implementation process 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, using callback functions becomes crucial, such as AJAX requests. If the callback function is used for processing, the code can continue with other tasks without being empty. In actual development, asynchronous calls are often used in javascript, and it is even strongly recommended here!

The following is a more comprehensive example of loading XML files using AJAX, and the call () function is used to call 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 (): // perform Functional Inspection on IE window. ActiveXObject? New ActiveXObject ("Microsoft. XMLHTTP "): undefined; httpRequest. onreadystatechange = function () {if (httpRequest. readystate === 4 & httpRequest. status = 200) {// status 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 is output first

Asynchronous request processing means that when we start the request, we will tell them to call our function when they are completed. In actual situations, the onreadystatechange event handler must consider 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, so it is not executed immediately.

Finally, the second console. log statement is executed first, because the callback function is not executed until the request is complete.

The above example is not easy to understand. Let's 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 variable. This is because the scopes in javascript are lexical. Function-based execution is in the scope that defines them (the scope inside foo in the preceding example), rather than in the scope that runs this function. As long as f is defined in foo, it can access all the variables defined in foo, even if the execution of foo has ended. Because its scope is saved, only the returned function can access the saved scope. Returning an embedded anonymous function is the most common method to create a closure.

What is callback?

Check the Callback _ (computer_programming) entries of the Wiki:

In computer programming, a callback is a reference to a piece of executable code that is passed as an argument to other code.

JQuery document How jQuery Works # Callback_and_Functio... entry:

A callback is a function that is passed as an argument to another function and is executed after its parent function has completed. the special thing about a callback is that functions that appear after the "parent" can execute before the callback executes. another important thing to know is how to properly pass the callback. this is where I have often forgotten the proper syntax.

Encyclopedia: callback Functions

A callback function is a function called by a function pointer. If you pass the pointer (address) of a function as a parameter to another function, when this pointer is used to call the function to which it points, we will say this is a callback function. The callback function is called by another party when a specific event or condition occurs instead of by the implementer of the function. It is used to respond to the event or condition.

Therefore, callback is essentially a design pattern, and the design principles of jQuery (including other frameworks) follow this pattern.

In JavaScript, the callback function is defined as: function A is passed to another function B as A parameter (function reference), and function B executes function. 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 Asynchronization. callback is often used in synchronous (blocking) scenarios. For example, a callback function is required to be executed after certain operations.

Example
An example of using callback 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(){}


Example of asynchronous callback:

$ (Document ). ready (callback); $. ajax ({url: "test.html", context: document. body }). done (function () {$ (this ). addClass ("done ");}). fail (function () {alert ("error ");}). always (function () {alert ("complete") ;});/** note that ajax requests are indeed asynchronous, however, this request is a new thread request from the browser. When the Request status changes, if the callback has been set previously, this asynchronous thread generates a state change event, which is placed in the processing queue of the JavaScript engine to be processed. */

When will the callback be executed?

The callback function is generally last executed in a synchronous situation, but may not be executed in an asynchronous situation because the event is not triggered or the conditions are not met.

Usage of callback Functions

Resource loading: callback is executed after js files are dynamically loaded, callback is executed after iframe is loaded, callback for ajax operations, callback for image loading completion, AJAX, and so on.
DOM events and Node. js events are based on callback mechanisms (Node. js callbacks may cause multi-layer callback nesting issues ).

The latency of setTimeout is 0, which is often used. The settimeout function is actually a callback.

Chained call: When a chained call is made, it is easy to implement chained call in the setter method (or in a method that does not return a value), while getter) it is relatively difficult to implement chained call, because you need the iterator to return the data you need instead of the this pointer. If you want to implement chained method, you can use the callback function to call the setTimeout and setInterval functions to obtain their return values. Because both functions are asynchronous, that is, their call sequence and the main process of the program are relatively independent, there is no way to wait for their return values in the subject, when they are opened, the program will not stop and wait. Otherwise, the meaning of setTimeout and setInterval will be lost. Therefore, it is meaningless to use return, and only callback can be used. Callback notifies the proxy function of the result of timer execution for timely processing.

Passing callback Functions

As mentioned above, function references or function expressions must be passed as parameters.

Pai.get('myhtmlpage.html ', myCallBack); // This is the correct example. get('myhtmlpage.html', myCallBack ('foo', 'bar'); // This is an error. What about parameters? Pai.get('myhtmlpage.html ', function () {// use the function expression myCallBack ('foo', 'bar') with parameters ');});


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 ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.