Javascript callback function details _ basic knowledge

Source: Internet
Author: User
This article discusses the usage of JavaScript Functions, callback functions, callback functions, callback modes, and function expressions. Callback Function Definition

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.

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.

The Code is as follows:


Var func1 = function (callback ){
// Do something.
(Callback & typeof (callback) === "function") & callback ();
}
Func1 (func2 );
Var func2 = function (){
}

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 the chained method, you can use the callback function to implement it.

SetTimeout and setInterval functions call 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.

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.

The Code is as follows:


// You can create a function in this way.
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.
  

The Code is as follows:


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 );
}); // Random number between 10 and 20

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.
  

The Code is as follows:


Function fn (url, callback ){
Var httpRequest; // create XHR
HttpRequest = window. XMLHttpRequest? New XMLHttpRequest ():
Window. ActiveXObject? New ActiveXObject ("Microsoft. XMLHTTP"): undefined; // performs a functional test on IE.

HttpRequest. onreadystatechange = function (){
If (httpRequest. readystate === 4
& HttpRequest. status === 200) {// status determination
Callback. call (httpRequest. responseXML );
}
};
HttpRequest. open ("GET", url );
HttpRequest. send ();
}

Fn ("text. xml", function () {// call a 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:

The Code is as follows:


Function foo (){
Var a = 10;
Return function (){
A * = 2;
Return;
};
}
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.

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.