Anonymous functions are functions that are declared without a name.
For example (using jQuery):
$.each(array, function(i,v){
alert(v);
});
The function here is anonymous, it is created just for this $.each
call.
A closure is a type of function (it can be used in an anonymous function, or it can be named), where the parameters passed into it are 'captured' and stay the same even out of scope.
A closure (in JavaScript):
function alertNum(a){
return function(){
alert(a);
}
}
The closure returns an anonymous function, but it does not have to be an anonymous function itself.
Continuing on the closure example:
alertOne = alertNum(1);
alertTwo = alertNum(2);
alertOne
and alertTwo
are functions that will alert 1 and 2 respectively when called.