Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why some people write a function like $(function( $ )

I know that code like $(function( $ ) does not make any sense, but I have find this sort of code at various places including todomvc.

There is a reason writing functions like jQuery(function( $ ) to resolve any potential conflict of $ used by any other library, but not $function($).

like image 605
Asif Mushtaq Avatar asked Feb 14 '13 06:02

Asif Mushtaq


2 Answers

There is no reason to use

$(function($))...

If you use the dollar sign in the beginning of the line you rely on that it's a jQuery object, so if you pass the jQuery object later on as a parameter to avoid conflicts, why didn't you use it on the first place? It's too later for that now...

The right way to use it is with:

(function($){ // The dollar variable is a parameter.
   $(function(){ // You use the $ variable only inside the function.
   });
})(jQuery); // jQuery is passed as a parameter.

$.somePrototypeFunctionHere(); // Here the dollar variable can be something else.
like image 77
gdoron is supporting Monica Avatar answered Oct 21 '22 18:10

gdoron is supporting Monica


It's useless

This form is not useful at all:

$(function($) {
});

It will work ONLY if there are no other libraries that could override $ (e.g. prototype).

How it could be useful

Since jQuery passes itself as the first argument to the DOM ready event handler function, this is how you could make good use of it:

jQuery(function($) {
    // this === document
    // $ === jQuery
});

The proof of this behaviour can also be found in the source:

readyList.resolveWith( document, [ jQuery ] );

It maps this to document and the first argument to your ready function to jQuery. The reason why the code looks a bit non-obvious is because the ready event is handled using Deferred.

The equivalent

The somewhat equivalent notation is this:

(function($) {
  $(function() {
  }
}(jQuery));

This would be preferred if you're doing more things outside of the ready handler, which actually happens more often than you think.

like image 24
Ja͢ck Avatar answered Oct 21 '22 17:10

Ja͢ck