如何将回调函数作为参数传递给另一个函数

96

我刚开始接触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);
}

可能是在JavaScript中更好地理解回调函数的方法的重复问题。 - ninjagecko
6个回答

146

是的。函数引用就像其他对象引用一样,您可以随心所欲地传递它们。

下面是一个更具体的示例:

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); // logs "Hello from foo!"

您还可以为 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); // logs "1 + 2 = 3"


13

同时,也可能很简单:

if( typeof foo == "function" )
    foo();

11

3
当然可以,函数是对象并且可以传递,但你必须先声明它:
function firstFunction(){
    //some code
    var callbackfunction = function(data){
       //do something with the data returned from the ajax request
     }
    //a callback function is written for $.post() to execute
    secondFunction("var1","var2",callbackfunction);
}

一个有趣的事情是,你的回调函数也可以访问你在firstFunction()中声明的所有变量(在JavaScript中,变量具有局部作用域)。

0

CoffeeScript的示例:

test = (str, callback) ->
  data = "Input values"
  $.ajax
    type: "post"
    url: "http://www.mydomain.com/ajaxscript"
    data: data
    success: callback

test (data, textStatus, xhr) ->
  alert data + "\t" + textStatus

在 JavaScript 中,-> 代表什么意思?@nothing-special-here - shenkwen
-> is just a normal function.var test = function(str, callback) { ajax call } - Barry
@shenkwen 一个细箭头 -> 是 CoffeeScript 语法,不是 JavaScript,当编译成 JavaScript 时,它只是表示普通的 JavaScript 函数。JavaScript 也有类似的箭头函数 https://www.w3schools.com/Js/js_arrow_function.asp - Bryan

0
你可以像这样使用JavaScript的回调函数:
var a;

function function1(callback) {
 console.log("First comeplete");
 a = "Some value";
 callback();
}
function function2(){
 console.log("Second comeplete:", a);
}


function1(function2);

或者是 JavaScript Promise:

let promise = new Promise(function(resolve, reject) { 
  // do function1 job
  let a = "Your assign value"
  resolve(a);
});

promise.then(             

function(a) {
 // do function2 job with function1 return value;
 console.log("Second comeplete:", a);
},
function(error) { 
 console.log("Error found");
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接