Wee*_*iat 76 javascript ajax callback call
我是ajax和回调函数的新手,请原谅我,如果我的概念都错了.
问题:我可以将回调函数作为参数发送给另一个执行回调的函数吗?
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);
}
Run Code Online (Sandbox Code Playgroud)
T.J*_*der 118
对.函数引用就像任何其他对象引用一样,您可以将它们传递给您的内容.
这是一个更具体的例子:
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!"Run Code Online (Sandbox Code Playgroud)
您还可以传递参数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"Run Code Online (Sandbox Code Playgroud)
Bra*_*rad 12
另外,可以很简单:
if( typeof foo == "function" )
foo();
Run Code Online (Sandbox Code Playgroud)
nin*_*cko 11
如果你谷歌,javascript callback function example你将获得更好地理解JavaScript中的回调函数
这是如何做回调函数:
function f() {
alert('f was called!');
}
function callFunction(func) {
func();
}
callFunction(f);
Run Code Online (Sandbox Code Playgroud)