7

Is this:

    ($.fn.myFunc = function() {
       var Dennis = function() { /*code */ }
       $('#Element').click(Dennis);
    })();

equivalent to:

    ($.fn.myFunc = function() {
       $('#Element').click(function() { /*code */ });
    })();

If not, can someone please explain the difference, and suggest the better route to take for both performance, function reuse and clarity of reading.

Thanks!

4 Answers 4

8

The only difference is that the former provides a reference to the function.

Thus, you can do this:

($.fn.myFunc = function() {
   var Dennis = function() { /*code */ }
   $('#Element').click(Dennis);

   Dennis();
})();

Which isn't possible with the latter.

This can be useful. For example, I may want the click to manipulate part of the page, but I also want to do it on page load. I could do so with:

$(function(){ 

    var manipulateSomething = function() {
        // do stuff
    };

    // do it on click
    $("#Element").click(manipulateSomething);

    // and do it right now (document.ready)
    manipulateSomething();

});

(Aside: You wouldn't call $("#Element").click(); to accomplish this unless you wanted ALL the click handlers on #Element to fire.)

Sign up to request clarification or add additional context in comments.

Comments

0

It's the same. I usually go with the second one, the anonymous function route.

The only reason to name your function inline, as in the first example, is if you need to use it again, perhaps later in the function, or if you want to be very clear what the function is. But even in that case, if the Dennis function were to take arguments, you would still need to use a new function scope in your call to pass those arguments along.

Anonymous function closures are the more robust pattern.

Comments

0

the second one looks prettier :) but its the same

Comments

0

Yes, the anonymous function is clearer though, without adding superfluous named functions which are called instantly.

If you really want to put a name there, you can. Names are generally only put there to make them recursive though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.