简体   繁体   中英

callback function meaning

javascript中回调函数的含义是什么?

JavaScript's "callback" is function object that can be passed to some other function (like a function pointer or a delegate function), and then called when the function completes, or when there is a need to do so. For example, you can have one main function to which you can pass a function that it will call...

Main function can look like this:

function mainFunc(callBack)
{
    alert("After you click ok, I'll call your callBack");

    //Now lets call the CallBack function
    callBack();
}

You will call it like this:

mainFunc(function(){alert("LALALALALALA ITS CALLBACK!");}

Or:

function thisIsCallback()
{
    alert("LALALALALALA ITS CALLBACK!");
}

mainFunc(thisIsCallback);

This is extensively used in javascript libraries. For example jQuery's animation() function can be passed a function like this to be called when the animation ends.

Passing callback function to some other function doesn't guarantee that it will be called. Executing a callback call ( calBack() ) totally depends on that function's implementation.

Even the name "call-back" is self-explanatory... =)

It's just a name for a function that should be called back after something.

It's often used with XMLHttpRequest:

var x = new XMLHttpRequest();
x.onreadystatechange = function(){
    if(x.readyState == 4){
        callbackfunction(x.responseText);
    }
}
x.open('get', 'http://example.com/', true);
x.send(null);

callbackfunction is just a plain function, in this case:

function callbackfunction(text){
    alert("I received: " + text);
}

Besides just being a function, a callback function is an enabler for asynchronous application design.

Instead of calling a function and waiting for the return value(s), potentially locking up the thread or the entire PC or UI on single threaded systems while you wait, with the async pattern you call a function, it returns before finishing, and then you can exit your code (return back to the calling OS, idle state, run loop, whatever...). Then later, the OS or asynchronous function calls your code back. The code you want it to call back is usually encapsulated in something called a "callback function". There are other uses, but this is a common one in OOP UI frameworks.

With the latest iOS 4.x, you can also use nameless "blocks" for the callback. But languages that don't have blocks (or anon closures under another name) use functions for function callbacks.

You can simply use the below statement onClick event of back button:

OnClick="javascript:history.go(-1)"

it will work to take you back to your previous page which you had visited recently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM