Tell you what is a JavaScript callback function

Source: Internet
Author: User

Callback functions are very important in JavaScript and they are almost ubiquitous. Like other more traditional programming languages, there is a callback function concept, but it is very strange that there are few online tutorials to talk about the callback function, but there is a bunch of call () and apply () functions, or some short examples of using callback.

  Functions are also objects

To figure out the callback function, you first have a clear understanding of the rules of the function. In JavaScript, the function is rather strange, but it is indeed an object. To be precise, a function object is created with a function () constructor. The function object contains a string that contains the JavaScript code for the functions. If you're transferring from C or Java, it might seem odd how the code might be a string. But for JavaScript, this is common. The difference between the data and the code is very vague.

?
123 //可以这样创建函数varfn = newFunction("arg1", "arg2", "return arg1 * arg2;");fn(2, 3); //6

One benefit of 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).

  Transfer function as callback

It is easy to pass a function as a parameter.

?
12345678 function FN (arg1, Arg2, callback) {   var num = Math.ceil (Math.random () * (ARG1-ARG2) + arg2);     callback (num); //delivery results }  FN ( Ten, 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, maybe even a little silly, why not return the results normally? But when it comes to the need to use a 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 that is structured as 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 finish 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 the callback function is used for processing, the code can proceed with other tasks without having to wait. In practice, asynchronous calls are often used in JavaScript, and even here it is highly recommended!

The following is a more comprehensive example of using AJAX to load an XML file, and using the call () function to invoke a callback function in the context of the request object (requested objects).

?
12345678910111213141516171819 function fn(url, callback){ var httpRequest;    //创建XHR httpRequest = window.XMLHttpRequest ? new XMLHttpRequest() :   //针对IE进行功能性检测    window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : undefined;  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 it's done. In fact, the onReadyStateChange event handler also takes into account 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 Async 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 executes until the request is complete.

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

?
12345678910 function foo () {   var a = ten;   return function () {    a *= 2;    return a;    }; } var f = foo (); f (); //return. f (); //return.

function is called externally, the variable a can still be accessed. This is because the scopes in JavaScript are lexical in nature. Functions run in the scope in which they are defined (within the scope of Foo inside the example above), not in 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 preserved, only the function that is returned can access the saved scope. Returning an inline anonymous function is the most common means of creating closures.

What is a callback?

See Wiki's Callback_ (computer_programming) Entry:

In computer programming, a callback are a reference to a piece of executable code that's passed as an argument to other CO De.

jquery document how jquery works#callback_and_functio ... Entry:

A callback is a function so is passed as an argument to another function and are executed after it parent function has C ompleted. The special thing about a callback was that functions that appear after the "parent" can execute before the callback Execut Es. Another important thing to know is what to properly pass the callback. This is where I have often forgotten the proper syntax.

Encyclopedia: Callback function

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

Therefore, callbacks are essentially a design pattern, and the design principles of jquery (including other frameworks) follow this pattern.

In JavaScript, the callback function is specifically defined as: function A is passed as a parameter (function reference) to another function B, and this function B executes function A. Let's just say that function A is called a callback function. If there is no Name (function expression), it is called an anonymous callback function.

So callback is not necessarily used for asynchrony, and callbacks are often used in scenarios where general synchronization (blocking) is required, such as executing a callback function after certain operations have been performed.

Example
An example of using callbacks in a synchronous (blocking) purpose is to execute FUNC2 after the FUNC1 code execution is complete.

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


Examples of asynchronous callbacks:

?
123456789101112 $(document).ready(callback);$.ajax({ url: "test.html", context: document.body}).done(function() {  $(this).addClass("done");}).fail(function() { alert("error");}).always(function() { alert("complete"); });/**注意的是,ajax请求确实是异步的,不过这请求是由浏览器新开一个线程请求,当请求的状态变更时,如果先前已设置回调,这异步线程就产生状态变更事件放到 JavaScript引擎的处理队列中等待处理。*/

When is the callback executed?

Callback functions, which are typically executed in a synchronous context, may not be executed in an asynchronous context because the event is not triggered or the condition is not satisfied.

Use of callback functions

Resource loading: Execute callback after dynamically loading JS file, execute callback after loading IFRAME, Ajax operation Callback, image loading complete execution callback, Ajax and so on.
DOM events and node. JS events are based on a callback mechanism (the node. JS callback may have multiple layers of callback nesting issues).

SetTimeout delay Time is 0, this hack is often used, settimeout call function is actually a callback embodiment

Chained invocation: When chaining calls, it is easy to implement chained calls in the evaluator (setter) method (or in a method that does not have a return value in itself), and the accessor (getter) is relatively bad for chaining calls because you need the accessor to return the data you need instead of the this pointer. If you want to implement a chained method, you can use a callback function to implement SetTimeout, SetInterval function call to get its return value. Since all two functions are asynchronous, that is, their call timing and the program's main process 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 it will lose the meaning of settimeout and setinterval, So with return there is no point, only using callback. The meaning of callback is to notify the agent function of the result of the timer execution to deal with it in time.

Delivery of callback functions

It says that you want to pass a function reference or function expression as a parameter.

?
12345 $.get ( ' myhtmlpage.html ' //This is the right $.get ( ' myhtmlpage.html ' , Mycallback ( ' foo ' " Bar ' //This is wrong, then take parameters? $.get ( ' myhtmlpage.html ' function () { //using function expressions with parameters Mycallback ( ' foo ' " Bar '


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


Tell you what is a JavaScript callback function

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.