JavaScript:将参数传递给回调函数

2022-08-29 23:44:09

我正在尝试将一些参数传递给用作的函数,我该怎么做?callback

这是我的尝试:

function tryMe(param1, param2) {
  alert(param1 + " and " + param2);
}

function callbackTester(callback, param1, param2) {
  callback(param1, param2);
}

callbackTester(tryMe, "hello", "goodbye");

答案 1

如果你想要一些稍微更通用的东西,你可以像这样使用参数变量:

function tryMe(param1, param2) {
  alert(param1 + " and " + param2);
}

function callbackTester(callback) {
  callback(arguments[1], arguments[2]);
}

callbackTester(tryMe, "hello", "goodbye");

但除此之外,您的示例工作正常(可以代替测试器)arguments[0]callback


答案 2

这也将起作用:

// callback function
function tryMe(param1, param2) {
  alert(param1 + " and " + param2);
}

// callback executer 
function callbackTester(callback) {
  callback();
}

// test function
callbackTester(function() {
  tryMe("hello", "goodbye");
});

另一种情况:

// callback function
function tryMe(param1, param2, param3) {
  alert(param1 + " and " + param2 + " " + param3);
}

// callback executer 
function callbackTester(callback) {
  //this is the more obivous scenario as we use callback function
  //only when we have some missing value
  //get this data from ajax or compute
  var extraParam = "this data was missing";

  //call the callback when we have the data
  callback(extraParam);
}

// test function
callbackTester(function(k) {
  tryMe("hello", "goodbye", k);
});