Jump to content

What is the purpose of Anonymous Functions?


spence911

Recommended Posts

They have two primary uses:

 

1. As a callback for another function and

2. To create a closure

 

A lot of the time for a callback, you only need a small couple of lines function. Rather than creating named functions for all these callbacks, it's far easier (and more reader-friendly typically) to just do a short anonymous function. For example:

$('.something').each(function(idx,ele){
   console.log(ele); //do something with each element
});
//or
$('.something').slideUp(function(){
   console.log('done sliding'); //Do something when the animation finishes
});
If you didn't use anonymous functions you'd either have to name them every function, or change the code, for example:

function dotSomethingIterationBody(idx,ele){
   console.log(ele); //do something with each element   
}

function dotSomethingAnimationFinished(){
   console.log('done sliding'); //Do something when the animation finishes
}

{
   $('.something').each(dotSomethingIterationBody);
   //or change to a loop
   for (var idx=0,items=$('.something'); idx<items.length; idx++){
      var ele = items[idx];
      console.log(ele); //do something with each element   
   }
}

$('.something').slideUp(dotSomethingAnimationFinished);

In a large application it is simply impractical to try and name every function like that.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.