purpose of callbacks in javascript

2019-08-19 02:40发布

Maybe someone mark my question as duplicate or else but i am confusing about callback in JavaScript. I read from here a following piece of code

getText = function(url, callback) // How can I use this callback?
{
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
    if (request.readyState == 4 && request.status == 200)
    {
        callback(request.responseText); // Another callback here
    }
}; 
request.open('GET', url);
request.send();
}
function mycallback(data) {
    alert(data);
}
getText('somephpfile.php', mycallback); //passing mycallback as a method

and now if i change the above code and remove callbacks like following

getText = function(url) //Also remove from here  How can I use this callback?
{
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
    if (request.readyState == 4 && request.status == 200)
    {
        mycallback(request.responseText); //Now here i simply call that function
    }
}; 
request.open('GET', url);
request.send();
}
function mycallback(data) {
    alert(data);
}
getText('somephpfile.php'); //Remove (passing mycallback as a method)

So now what is difference now? If no difference then why use callbacks

1条回答
爷、活的狠高调
2楼-- · 2019-08-19 03:04

So now what is difference now? If no difference then why use callbacks

Your first function is more general (reusable). You can do all of these:

getText('somephpfile.php', console.log); // or
getText('somephpfile.php', alert); // or
getText('somephpfile.php', mycallback); // or
getText('somephpfile.php', yourcallback); // or
getText('somephpfile.php', whatever);

which will behave differently. In your second function, the getText cannot be used for anything else but alerting ajax data.

查看更多
登录 后发表回答