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($)
.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With