简体   繁体   中英

Is passing a javascript callback function as a parameter required?

In everything I've read thus far, callback functions are passed as arguments into other functions:

function mycallback(){
    //dosomething
}

function mainfunc(mycallback){
    //do something else
    mycallback();
}

mainfunc(mycallback);

Which works as you would expect, great. My question is if the passing of the callback function as an argument into the mainfunc is requried? It seems if you omit this:

function mycallback(){
    //dosomething
}

function mainfunc(){
    //do something else
    mycallback();
}

mainfunc();

it works fine, and is identical to the first example. But I don't see people using callbacks in this way. Is there a reason? What am I missing?

Callbacks are best used when you have asynchronous tasks.

Let's say mainfunc is an async operation.

  • In your first example, you handed a specific callback to mainfunc . This gives you flexibility to the caller to assign what function to execute after the operation.

  • The second example, you hardcoded the callback. Unless you have a reason to do so, like a predetermined post-processing function, this is not flexible.

Technically, yes, you can use your functions like that. The reason for passing a function as a parameter, is the same reason you would have for passing anything as a parameter.

mainfunc(eatSevenBurritos);
mainfunc(eatTwoChimichangas);

Under certain conditions, maybe you'd rather eat 7 burritos while going through mainfunc. Maybe under some other condition, you'd rather eat 2 chimichangas while going through mainfunc.

If you're always going to be running the same function, then go ahead and code it in there if you can. There's no point adding pointless complexity. But if you need that behavior to change, you need to treat it as a parameter.

When folks talk about "first class functions" this sort of behavior is what they mean. Being able to treat functions as a parameter. Because behavior is a type of data.

You second approach works fine if you want a single function to handle all callbacks.

Often when you call a method that uses a callback, you want it to different things in the callback depending on when you call it and from where. Instead of handling all different situations in a single callback function (which then has to be aware of which situation it is), you can simply use one callback function for each specific situation.

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