According to jQuery online document, if we want to avoid naming conflict, we could write our script like the followings:
jQuery(document).ready(function($) {
// Code using $ as usual goes here.
});
While I feel the following approach much easier to understand:
(function($){ //function to create private scope with $ parameter
//private scope and using $ without worry of conflict
})(jQuery); //invoke nameless function and pass it the jQuery object
The first approach seems harder for me to consume. My guess here is (with the first approach) that later on the anonymous function will be called behind the scene which will take jQuery as its parameter.
However I am not sure if my thinking is right. Could some one help me with it?
Thank you.
The former is different than the latter. You should not try to equate them:
Example #2 (
function($) ...) is a plain JavaScript construct. It is an anonymous function that is called immediately withjQueryas the argument and$as the parameter (which resolves to thejQueryargument passed in).Example #1 is
jQueryspecific.jQuery‘s internal workings have it so that the first argument passed in to thedocument.readyfunction isjQueryitself, and you can name it whatever you want (in this case,$). Note thatjQuery(document).readyalso has its own unique functionality! It is likely to work differently than Example #2I would suggest that you put all your JavaScript right before
</body>in your HTML. In that case, the above two examples should work in more or less the same way.As @elclanrs indicates, you can also use
jQuery.noConflict(). The return value will act as the newjQueryvariable. Some people like to use$$.