Jump to content

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.
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.