views:

40

answers:

1

Hi,

I am trying to understand callback functions in javascript.

There is a function something like

function load() {

 var func = function(data){
  ///

 };
}

Can anyone explain me from where the parameter "data" will be returned, as I dont see any variable declared in the file.

+2  A: 

In JavaScript, functions are first class objects. You could store them in objects (variables) and pass them around as arguments to functions. Every function is actually a Function object.

You don't have a callback function in that example. You'd have one when you pass a function as an argument to another function.

This is a function that invokes a callback function when it is ready:

function load (ready_callback) {
   // do some stuff

   ready_callback();
}

Which can be invoked as follows:

function callback () {
   alert('Ready');
}

load(callback);

Or:

var callback = function () {
   alert('Ready');
}

load(callback);

Or:

load(function () {
   alert('Ready');
});

The above three example are pretty much equivalent.

Callback functions are typically used for event handling and asynchronous methods. One example is the setTimeout() method, which invokes a callback function when a timeout expires:

var timerCallback = function () {
   alert('Timeout Expired!');
}

setTimeout(timerCallback, 5000);  // Set the timeout to 5 seconds
Daniel Vassallo