How to Run a Function Passed as a Parameter in JavaScript
We’ll often pass functions as parameters in JavaScript in order to run it as a callback function.
Generally, we can just invoke the function normally using parentheses.
Using a Normal Function Call
function callback(param) {
console.log(param);
}
function run_callback(param, callback_function) {
callback_function(param);
}
run_callback("Hello", callback); // "Hello"
Using call()
Interestingly enough, we can also set the execution context of the callback function using call()
. By default, this context is window
, but we can change this.
Using call()
, we can explicitly set what the value of this
will be in the callback function.
function callback() {
console.log(this);
}
function run_callback(param, callback_function) {
callback_function.call(param);
}
run_callback("Hello", callback); // String {"Hello"}