views:

137

answers:

2

Are the following assumptions accurate?

1) execute immediately

(function(){
})();

2) execute on document ready

$(document).ready(function(){
});

3) shorthand for on document ready

$(function(){
});

4) alternative shorthand for on document ready for avoiding cross script conflicts

(function($) {
})(jQuery);
+3  A: 

Yes your definitions are correct, for the first 3 :)

Though, unless you need a closure, a statement will execute immediately, no reason to wrap it like #1 has (there are certainly plenty of valid times you need a closure, just noting if you don't...it's superfluous).

Number 4 however is not correct, (function($) { })(jQuery); is not tied to any event, it's just a closure so that $ === jQuery inside of it, so you can use the $ shortcut:

(function($) { 
  //You may use $ here instead of jQuery and it'll work...even if $ means
  //something else outside of this closure, another library shortcut for example
})(jQuery);
Nick Craver
Very informative answer. Is Number 4 mainly used just in case $ has been overwritten in the global scope since jQuery file was loaded?
Dr. Frankenstein
@yaya3 - Yes, usually as a result of [`.noConflict()`](http://api.jquery.com/jQuery.noConflict/) to let another library control `$`. However if you wanted `document.ready` and no conflicts, there's a short version as well, jQuery passes itself as a parameter to the ready handler so `jQuery(document).ready(function ($) { });​` or the shorter `jQuery(function ($) { });​` are getting `$` passed in, more local so `$ === jQuery` inside as well...and the code's triggered on `document.ready`, nice and neat. Or use any other name :), e.g. `jQuery(function (myVar) { myVar('#myElem').hide(); });​`
Nick Craver
Awesome, learnt a lot here. Thanks
Dr. Frankenstein
+1  A: 

Here's the #4 you were looking for:

jQuery(function ($) {
});

It will run on document.ready, within a namespace, and with jQuery defined as $.

Magnar