且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否需要传递一个javascript回调函数作为参数?

更新时间:2023-02-18 21:12:39

如果你想要一个函数处理所有的回调,你的第二种方法很好。

通常当你调用一个使用回调的方法时,你需要它在回调中的不同的东西取决于什么时候调用它和从哪里。而不是在单个回调函数中处理所有不同的情况(然后必须知道它是哪种情况),您可以为每种特定情况简单地使用一个回调函数。


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?

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.