vitto vitto - 13 days ago 5
Javascript Question

JavaScript: Passing parameters to a callback function

I'm trying to pass some parameter to a function used as callback, how can I do that?

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

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

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

Answer

If you want something slightly more general, you can use the arguments variable like so:

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

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

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

But otherwise, your example works fine (arguments[0] can be used in place of callback in the tester)