Callback functions are used in JavaScript (JS) extensively. They are required for AJAX/XHR, event handling, and in popular JS libraries. However, passing around functions as arguments can cause headaches, especially for beginner JS programmers.
Problems with binding/this
One of the biggest problems with passing functions as callbacks is this and what it
refers to. You usually run into the problem when passing an object's method as a
callback function. Another way to encounter this problem is by passing as a callback a function that
expects to be bound to a certain type of object. You'll usually get an error stating that
this.someProperty is undefined. You can resolve this with
Function.apply, Function.call or a closure. For example:
//using Function.call
takesCallback(
function callbackProxy(argOne, argTwo){
//assume myFunction is already defined
myFunction.call(myObject, argOne, argTwo);
}
);
//or using Function.apply
takesCallback(
function callbackProxy(argOne, argTwo){
//assume myFunction is already defined
myFunction.apply(myObject, [argOne, argTwo]);
}
);
//or using a closure
takesCallback(
function callbackProxy(argOne, argTwo){
//assume myObject is already defined
myObject.myMethod(argOne, argTwo);
}
);
In the code above, the function takesCallback takes a callback function as its
only argument and calls that function at a later time with two arguments. The function, callbackProxy is
a wrapper function that takes the arguments and passes them to the real callback, while ensuring
that the function is bound to the correct object.