Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery and function scope

Tags:

jquery

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!

like image 622
Jason Avatar asked Apr 29 '10 00:04

Jason


1 Answers

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.)

like image 127
Joel Avatar answered Oct 18 '22 08:10

Joel