hmqcnoesy
hmqcnoesy

Reputation: 4225

jQuery Succinctly syntax explanation

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.

Upvotes: 5

Views: 400

Answers (2)

Elliot Bonneville
Elliot Bonneville

Reputation: 53311

Yes, this is a succinct way to avoid jQuery conflict with other libraries. It's known as a "closure". In other words, the variable $ is scoped to that function and can be used without harm outside of it.

Upvotes: 4

ThiefMaster
ThiefMaster

Reputation: 318518

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)

Upvotes: 7

Related Questions