I'm trying to pass some parameter to a function used as callback
, how can I do that?
This is my try:
function tryMe(param1, param2) { alert(param1 + " and " + param2); } function callbackTester(callback, param1, param2) { callback(param1, param2); } callbackTester(tryMe, "hello", "goodbye");
To pass multiple arguments into a JavaScript callback function, we can use the spread operator. to create the someClass class that takes a callback function and params parameters. We set them both as values for properties of this . And we define the method method that calls this.
In JavaScript, when we pass a function to another function as a parameter, it is called a callback function. The function takes another function as a parameter and calls it inside. A callback function makes sure that a function will not run until the task completes.
function function1() { var variable1=12; function2(variable1); } function function2(val) { var variableOfFunction1 = val; // Then you will have to use this function for the variable1 so it doesn't really help much unless that's what you want to do. } i used the second way and it worked.
Arguments are Passed by Value The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.
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)
This would also work:
// callback function function tryMe(param1, param2) { alert(param1 + " and " + param2); } // callback executer function callbackTester(callback) { callback(); } // test function callbackTester(function() { tryMe("hello", "goodbye"); });
Another Scenario :
// 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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With