Matt
Matt

Reputation: 2509

Are anonymous functions more effecient over calling functions?

I'm just starting to learn about jQuery. I'm more of a html+css web designer so you can probably tell functions will take a little bit to adapt to, especially anonymous ones.

So what's the difference if between

$('p.expander').toggle(
   function() {
    $(this).prev().addClass('open');
   },
   function() {
    $(this).prev().removeClass('open');
  }
);

and say...

 function toggle1 () {  $(this).prev().addClass('open');}
 function toggle2 () {  $(this).prev().removeClass('open');}
 $('p.expander').toggle(toggle1, toggle2); 

Do you use anonymous functions if you're using it once? And if you're going to use functions more than once, you should call it?

And as the title states, is one more effecient than the other? Because it seems like 99% of the articles use anonymous articles. I find it hard to read the code sometimes because I forget what a semicolon or parenthesis is for.

Upvotes: 3

Views: 126

Answers (3)

gdoron
gdoron

Reputation: 150253

There is no performance difference between anonymous and unanonymous functions.
It's redundent to call the function a name if you call the function only once.

If you want to call the same function twice or more, You will have to name the function.

Upvotes: 1

Esailija
Esailija

Reputation: 140210

In that specific situation, there is no difference. But consider:

$(document).ready( function(){

    var a, b, c,
        d, e, f,
        g, h, i;


    $('p.expander').toggle(
       function() {
        $(this).prev().addClass('open');
       },
       function() {
        $(this).prev().removeClass('open');
      }
    );
});

vs

function toggle1 {  $(this).prev().addClass('open');}
function toggle2 {  $(this).prev().removeClass('open');}

$(document).ready( function(){

    var a, b, c,
        d, e, f,
        g, h, i;


    $('p.expander').toggle( toggle1, toggle2 );
});

In this scenario, the anonymous functions contain larger environment (use more memory) because they know about a, b, c, d, e, f, g, e, h, iunless the browser optimizes it.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

The name, that's the difference. Both are equivalent at runtime. It's just that if you define an anonymous function you cannot reuse it in other places. It is useful in scenarios where you do not intend to reuse this code. Use a named function when you want to reuse it.

Here's an example where we can reuse the named functions in multiple places:

$('p.expander').toggle(toggle1, toggle2); 
$.post('/foo/bar', toggle1);
$('a.foo').click(toggle2);

Upvotes: 1

Related Questions