Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Succinctly syntax explanation

Tags:

jquery

syntax

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.

like image 557
hmqcnoesy Avatar asked May 08 '12 14:05

hmqcnoesy


1 Answers

It creates a closure where $ === jQuery even 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 var and attaching functions to the window or this object)

like image 54
ThiefMaster Avatar answered Nov 11 '22 06:11

ThiefMaster