I have the book Jquery in Action, and it mentions these three functions when talking about removing conflict with other libraries. However, I don’t know what the difference is between them and do not understand the book’s explanation.
jQuery(function($) {
alert('I"m ready!');
});
var $ = 'Hi!';
jQuery(function() {
alert('$ = ' + $);
});
var $ = 'Hi!';
jQuery(function($) {
alert('$ = ' + $);
});
Does anyone know what the difference is? Thanks.
If you take a simplified version it might be more understandable. The first ready function is not doing much more than alerting. The other two are interesting.
Functions have scope, which means that when you use a variable inside one, it will go up in the hierarchy until it has been found.
In your second ready function, the
$will go up to theHi!as there is no other$if you go up starting inside the function.However, in the third ready block, the
$will not go to theHi!because it has a definition that is closer – the one passed as an argument (function($) {). This$will be the jQuery function (i.e. in that function$ == jQuery) as this is how jQuery’s ready feature is implemented.So:
Now your question is about conflict with other libraries. Other libraries (Prototype for example) also use the
$symbol as it is a convenient shortcut to calling the library. If you use the last ready function you provided, you can be sure that inside that function,$will refer to jQuery as jQuery passes itself to that function (as the first argument).In the second ready function,
$might also have been set to Prototype, for example, and you are not sure whether you are calling jQuery with$. In your example, it wasHi!and not jQuery. In case it’s Prototype it’s the same thing. Consider:On the other hand: