Making Callbacks in JavaScript?

By now,all jquery users shud be familiar with the term “callback”,Because JavaScript unlike other Languages that have thread,or that allow statements like

while(!Enumerator.next())<br>{<br>System.readByte(int);<br>}<br><br>

Javascript blocks any function while the loops are running,so a callback is needed to alert the developer that the function has been completed.

take for instance.Jquery uses a lot of callbacks take for instance.

$('#clickme').click(function() {<br>  $('#book').animate({<br>    opacity: 0.25,<br>    left: '+=50',<br>    height: 'toggle'<br>  }, 5000, function() {<br>    // Animation complete.<br>This here is a Callback and Most Callbacks are anonymous functions,functions with no name<br>  });<br>});<br><br>

However am teaching Pure Js since i don't really use Jquery(lacks Class Support) so lets do a simple callback


//Creates a function with 2 arguments<br>function ajax(a,callback)<br>{<br>if(a) //if the first argument is defined<br>{<br>var b=["json","xml","ati"]; //Here we declared an Array this will emulate an Ajax Return Data Set<br>}<br>if(callback) //If the second argument has been defined<br>return (callback(b)); //we call it like a function and pass the data as a parameter<br><br>}<br>//So we just pass a dummy data and create our anonymous function and our argument will be the return data from the inner function.<br>ajax("a",function(data){<br>console.log(data)}); //print  the array<br>

Although this is just a scratch concept to explain you still need to implement some sort of a data checking to see if the second argument is a function by using the typeof and the constructor property.