I just downloaded the jQuery Succinctly free ebook (here) from Syncfusion and started looking through the examples.
I see a lot of this type of thing:
<script> (function ($)
{
$('a').mouseenter(
function () { alert(this.id); });
})(jQuery);
</script>
I’m not sure why the author is using this syntax. The $ object is being passed into the anonymous function? Why? And what is the (jQuery) following the anonymous function for?
Is this simply a way to avoid conflicts with other libraries? It seems to me these examples could be written much more “succinctly” 🙂
Thanks.
It creates a closure where
$ === jQueryeven if$.noConflict()was used to remove the global jQuery$.That allows you to always use
$without having to care if the user is e.g. also using a framework such as prototype which also uses$.The closure also has the advantage that your variables/functions are not global unless you explicitely make them global (by not using
varand attaching functions to thewindoworthisobject)