Home  >  Article  >  Web Front-end  >  Detailed explanation of javascript callback function_Basic knowledge

Detailed explanation of javascript callback function_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:31:411475browse

Callback function definition

The callback function is a function called through a function pointer. If you pass a function pointer (address) as a parameter to another function, and when this pointer is used to call the function it points to, we say it is a callback function. The callback function is not called directly by the implementer of the function, but is called by another party when a specific event or condition occurs to respond to the event or condition.

In JavaScript, the specific definition of a callback function is: function A is passed as a parameter (function reference) to another function B, 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 for asynchronous use. Callback is often used in general synchronous (blocking) scenarios, such as requiring the execution of a callback function after performing certain operations.

Example
An example of using callbacks in synchronization (blocking), the purpose is to execute func2 after the execution of func1 code is completed.

Copy code The code is as follows:

var func1=function(callback){
//do something.
(callback && typeof(callback) === "function") && callback();
}
func1(func2);
var func2=function(){
}

Usage occasions of callback function
Resource loading: execute callback after dynamically loading js files, execute callback after loading iframe, ajax operation callback, execute callback after image loading is completed, AJAX, etc.

DOM events and Node.js events are based on the callback mechanism (Node.js callbacks may have problems with multi-layer callback nesting).
The delay time of setTimeout is 0. This hack is often used. The function called by settimeout is actually the embodiment of a callback

Chained calls: When chained, it is easy to implement chained calls in the assignor (setter) method (or in a method that does not return a value itself), but the getter (getter) is relatively difficult to implement. Implement chained calls, because you need the valuer to return the data you need instead of this pointer. If you want to implement a chained method, you can use a callback function to implement it

The function calls of setTimeout and setInterval get their return values. Since both functions are asynchronous, that is, their calling sequence is relatively independent of the main process of the program, there is no way to wait for their return values ​​in the body, and the program will not stop and wait when they are opened. Otherwise, the meaning of setTimeout and setInterval will be lost, so it is meaningless to use return, and callback can only be used. The meaning of callback is to notify the agent function of the result of timer execution for timely processing.

Functions are also objects

If you want to understand the callback function, you must first clearly understand the rules of the function. In JavaScript, functions are weird, but they are indeed objects. To be precise, a function is a Function object created using the Function() constructor. The Function object contains a string that contains the JavaScript code of the function. If you are coming from C or Java, this may seem strange. How can the code be a string? But with javascript, this is commonplace. The distinction between data and code is blurry.

Copy code The code is as follows:

//You can create functions 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 regular variables or objects (because code is literally just an object).

Passing function as callback

It’s easy to pass a function as a parameter.

Copy code The code is as follows:

function fn(arg1, arg2, callback){
var num = Math.ceil(Math.random() * (arg1 - arg2) arg2);
​ callback(num);//Transfer the result
}

fn(10, 20, function(num){
console.log("Callback called! Num: " num);
});//The result is a random number between 10 and 20

Maybe this seems cumbersome or even a bit stupid. Why don't you return the results normally? But when you have to use a callback function, you may not think so!

Stay out of the way

Traditional functions input data in the form of parameters and use return statements to return values. Theoretically, there is a return statement at the end of the function, which is structurally: an input point and an output point. This is easier to understand. A function is essentially a mapping of the implementation process between input and output.

However, when the function implementation process is very long, do you choose to wait for the function to complete processing, or use a callback function for asynchronous processing? In this case, it becomes crucial to use callback functions, for example: AJAX requests. If you use a callback function for processing, the code can continue to perform other tasks without waiting in vain. In actual development, asynchronous calls are often used in JavaScript, and it is even highly recommended here!

Below is a more comprehensive example of using AJAX to load an XML file, and uses the call() function to call the callback function in the context of the requested object.

Copy code 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;//Functional detection for IE
 
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 function
console.log(this); //Output after this statement
});

console.log("this will run before the above callback."); //This statement is output first

Our requests are processed asynchronously, which means that when we start the request, we tell them to call our function when they are completed. In actual situations, the onreadystatechange event handler must also consider the situation of request failure. Here 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 and therefore will not be executed immediately.

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

The above example is not easy to understand, so take a look at the following example:

Copy code The code is as follows:

function foo(){
var a = 10;
Return function(){
        a *= 2;
         return a;                                    };  
}
var f = foo();
f(); //return 20.
f(); //return 40.

When the function is called externally, the variable a can still be accessed. This is all because scope in JavaScript is lexical. Functions run in the scope in which they are defined (the scope inside foo in the above example), not the scope in which the function is run. As long as f is defined in foo, it can access all variables defined in foo, even if the execution of foo has ended. Because its scope will be saved, but only the returned function can access this saved scope. Returning a nested anonymous function is the most common way to create closures.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn