Passing arguments to callback functions
By default you cannot pass arguments to a callback function. For example:
function callback() {
console.log('Hi human');
}
document.getElementById('someelem').addEventListener('click', callback);
You can take advantage of the closure scope in Javascript to pass arguments to callback functions. Check this example:
function callback(a, b) {
return function() {
console.log('sum = ', (a+b));
}
}
var x = 1, y = 2;
document.getElementById('someelem').addEventListener('click', callback(x, y));
What are closures?
Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure ‘remembers’ the environment in which it was created. Check MDN Documentation to learn more.
So this way the arguments x
and y
are in scope of the callback function when it is called.
Another method to do this is using the bind
method. For example:
var alertText = function(text) {
alert(text);
};
document.getElementById('someelem').addEventListener('click', alertText.bind(this, 'hello'));
There is a very slight difference in performance of both methods, checkout jsperf.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOWA short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW