如何将回调作为参数传递给另一个函数 [英] How to pass a callback as a parameter into another function
本文介绍了如何将回调作为参数传递给另一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是ajax和回调函数的新手,如果我的概念都错了,请原谅我。
I'm new to ajax and callback functions, please forgive me if i get the concepts all wrong.
问题:我可以吗?将 回调函数 作为参数发送给另一个执行回调的函数?
Problem: Could i send a callbackfunction as a parameter to another function that will execute the callback?
function firstFunction(){
//some code
//a callback function is written for $.post() to execute
secondFunction("var1","var2",callbackfunction);
}
function secondFunction(var1, var2, callbackfunction) {
params={}
if (event != null) params = event + '&' + $(form).serialize();
// $.post() will execute the callback function
$.post(form.action,params, callbackfunction);
}
推荐答案
是的。函数引用就像任何其他对象引用一样,你可以将它们传递给你的内容。
Yup. Function references are just like any other object reference, you can pass them around to your heart's content.
这是一个更具体的例子:
Here's a more concrete example:
function foo() {
console.log("Hello from foo!");
}
function caller(f) {
// Call the given function
f();
}
function indirectCaller(f) {
// Call `caller`, who will in turn call `f`
caller(f);
}
// Do it
indirectCaller(foo); // alerts "Hello from foo!"
你也可以通过在 foo
的参数中:
You can also pass in arguments for foo
:
function foo(a, b) {
console.log(a + " + " + b + " = " + (a + b));
}
function caller(f, v1, v2) {
// Call the given function
f(v1, v2);
}
function indirectCaller(f, v1, v2) {
// Call `caller`, who will in turn call `f`
caller(f, v1, v2);
}
// Do it
indirectCaller(foo, 1, 2); // alerts "1 + 2 = 3"
这篇关于如何将回调作为参数传递给另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文