On the application _javascript technique of JavaScript callback function

Source: Internet
Author: User

Definition of a callback function

A callback function is a function called by a function pointer. If you pass the pointer (address) of a function to another function as an argument, when the pointer is used to call the function it points to, we say this is a callback function. A callback function is not invoked 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.
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 () {
}

Second, the use of callback function occasions

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 calls: when chained calls, it is easy to implement chained calls in the assignment (setter) method (or in a method that does not have a return value), 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 program's main stream 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 also lost the meaning of settimeout and setinterval, so use return has no meaning, can 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 do this by creating the function
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 result
}

fn (A, function (num) {
  console.log ("Callback called! NUM: "+ num); 
}"; /result is a 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) {//state judgment
     Callback.call ( httprequest.responsexml); 
    }
  ;
  Httprequest.open ("get", url);
  Httprequest.send ();
}

FN ("Text.xml", function () {//Call functions
  console.log (this); After this statement is output
});

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 = ten;
  return function () {
    a *= 2;
    return A;    
  };  
}
var f = foo ();
f (); return.
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.

The above is the entire content of this article, I hope to learn JavaScript program to help you.

Related Article

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.