问题描述
在我到目前为止阅读的所有内容中,回调函数作为参数传递给其他函数:
function mycallback {
// dosomething
}
function mainfunc(mycallback){
//做别的事
mycallback
}
mainfunc(mycallback);
我的问题是如果将回调函数作为参数传递给mainfunc是否需要?看起来如果你省略这个:
function mycallback(){
// dosomething
}
function mainfunc(){
//做别的事
mycallback();
}
mainfunc();
它工作正常,与第一个示例相同。但我没有看到人们以这种方式使用回调。有理由吗?
如果你想要一个函数处理所有的回调,你的第二种方法很好。
通常当你调用一个使用回调的方法时,你需要它在回调中的不同的东西取决于什么时候调用它和从哪里。而不是在单个回调函数中处理所有不同的情况(然后必须知道它是哪种情况),您可以为每种特定情况简单地使用一个回调函数。
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.
这篇关于是否需要传递一个javascript回调函数作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!