Getting a better understanding of callback functions in JavaScript Getting a better understanding of callback functions in JavaScript javascript javascript

Getting a better understanding of callback functions in JavaScript


You can just say

callback();

Alternately you can use the call method if you want to adjust the value of this within the callback.

callback.call( newValueForThis);

Inside the function this would be whatever newValueForThis is.


You should check if the callback exists, and is an executable function:

if (callback && typeof(callback) === "function") {    // execute the callback, passing parameters as necessary    callback();}

A lot of libraries (jQuery, dojo, etc.) use a similar pattern for their asynchronous functions, as well as node.js for all async functions (nodejs usually passes error and data to the callback). Looking into their source code would help!


There are 3 main possibilities to execute a function:

var callback = function(x, y) {    // "this" may be different depending how you call the function    alert(this);};
  1. callback(argument_1, argument_2);
  2. callback.call(some_object, argument_1, argument_2);
  3. callback.apply(some_object, [argument_1, argument_2]);

The method you choose depends whether:

  1. You have the arguments stored in an Array or as distinct variables.
  2. You want to call that function in the context of some object. In this case, using the "this" keyword in that callback would reference the object passed as argument in call() or apply(). If you don't want to pass the object context, use null or undefined. In the latter case the global object would be used for "this".

Docs for Function.call, Function.apply