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 callback in synchronization (blocking), the purpose is to execute func2 after the execution of func1 code is completed.
var func1=function(callback){ //do something. (callback && typeof(callback) === "function") && callback(); } func1(func2); var func2=function(){ }
Use occasions of callback function
Resource loading: callback is executed after dynamic loading of js file, callback is executed after iframe is loaded, ajax operation callback, callback is executed after image loading is completed, AJAX, etc. wait.
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.
Chain call: During chain call, in the assignor (setter) method It is easy to implement chained calls in a method (or a method that does not return a value itself), but it is relatively difficult to implement chained calls with a getter, because you need the getter to return the data you need instead of this pointer , if you want to implement a chain method, you can use the callback function to implement the function calls of
setTimeout and setInterval to 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.
Function is also an object
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.
//可以这样创建函数 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 the code is literally just an object).
Passing functions as callbacks
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);//传递结果 } fn(10, 20, function(num){ console.log("Callback called! Num: " + num); });//结果为10和20之间的随机数
Maybe this seems cumbersome or even a bit stupid. Why not return the results normally? But when you have to use a callback function, you may not think so!
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.
function fn(url, callback){ var httpRequest; //创建XHR httpRequest = window.XMLHttpRequest ? new XMLHttpRequest() : window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP" ) : undefined;//针对IE进行功能性检测 httpRequest.onreadystatechange = function(){ if(httpRequest.readystate === 4 && httpRequest.status === 200){ //状态判断 callback.call(httpRequest.responseXML); } }; httpRequest.open("GET", url); httpRequest.send(); } fn("text.xml", function(){ //调用函数 console.log(this); //此语句后输出 }); console.log("this will run before the above callback."); //此语句先输出
We request asynchronous processing, 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.
Ultimately, 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:
function foo(){ var a = 10; return function(){ a *= 2; return a; }; } var f = foo(); f(); //return 20. f(); //return 40.
函数在外部调用,依然可以访问变量a。这都是因为javascript中的作用域是词法性的。函数式运行在定义它们的作用域中(上述例子中的foo内部的作用域),而不是运行此函数的作用域中。只要f被定义在foo中,它就可以访问foo中定义的所有的变量,即便是foo的执行已经结束。因为它的作用域会被保存下来,但也只有返回的那个函数才可以访问这个保存下来的作用域。返回一个内嵌匿名函数是创建闭包最常用的手段。
The above is the detailed content of Detailed explanation of javascript callback function definition and usage examples. For more information, please follow other related articles on the PHP Chinese website!