Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain what function($) does in jQuery

Recently I was reading someone else's code, and came across this:

// Semicolon (;) to ensure closing of earlier scripting
// Encapsulation
// $ is assigned to jQuery
;(function($) {

     // DOM Ready
    $(function() {
        ...
  });

})(jQuery);

I understand the point of the leading ;, And I understand that $(function() { is the same as document ready, but what is the point of adding function($)?

I understand it's a closure, but since this is always being called at the global scope, it seems like you don't need to bother with it. The $(function() { will use the same global object either way, no?

Is it to safeguard against something, or is it a best practice for another reason?

like image 617
nycynik Avatar asked Oct 12 '12 14:10

nycynik


Video Answer


1 Answers

It's a common structure for a jQuery plugin. It safeguards against the $ identifier having been overwritten and used for something else. Inside the anonymous function, $ is always going to refer to jQuery.

Example:

$ = "oh no";
$(function() { //Big problem!
    //DOM ready
});

By introducing a new scope, you can ensure that $ refers to what you expect it to:

$ = "oh no";
(function($) { //New scope, $ is redeclared and jQuery is assigned to it

    $(function() { //No problem!
        //DOM ready
    }); 

}(jQuery));

The main reasoning behind this is that numerous other JavaScript libraries use $ as an identifier (e.g. PrototypeJS). If you wanted to use both Prototype and jQuery, you need to let Prototype have its $ identifier, but you probably don't want to write out jQuery every time you want to call a jQuery method. By introducing a new scope you allow jQuery to have its $ back in that execution context.

like image 91
James Allardice Avatar answered Oct 20 '22 00:10

James Allardice