This:
(function() { do some stuff } )();

is known as a closure. It just runs once and it does not leave around
any global variables (that is, if you also don't set any inside this
function also).

Compared to this:
function doSomething() { // do some stuff };

The doSomething variable will exist (globally) to be available for
access again. It will exist in memory, and may possibly "pollute" the
global namespace. This is usually a problem if you have a lot of other
Javascript that may have same variable name conflicts (e.g. multiple
Javascript libraries). In the first example, no such global variable
will exist. It will run once, and disappear.

In your example:
(function($) { do some stuff } )(jQuery);

The $ variable (local) has the value of the jQuery (global) variable,
therefore, inside your closure, you can use $ as your jQuery variable.


On Jul 25, 6:35 am, Aleksey <gabb...@gmail.com> wrote:
> Well, it's a common pattern that is used when creating a jQuery
> plugin.
> A common problem doing that is the use of a '$' sign, because other
> frameworks use it too as well. I didn't try to use some frameworks
> simultaneously yet, so I didn't encountered that problem by myself.
> One of the way is to use 'jQuery' instead of '$' ('$' is a shorthand
> of 'jQuery'), and to write, for example:
>
> jQuery('a').click(function() { });
> instead of
> $('a').click(function() { });
>
> But there is another way - this pattern allows you to use '$' in your
> jQuery code without the worry of malfunctioning.
>
> You can read more about the creating jQuery plugin in the following
> articles:http://blog.themeforest.net/tutorials/ask-jw-decoding-self-invoking-a...http://blog.jeremymartin.name/2008/02/building-your-first-jquery-plug...http://docs.jquery.com/Tutorials
>
> Good luck)
>
> On Jul 25, 4:04 pm, Kris <ilaymy...@yahoo.com> wrote:
>
> > What does this do?
> > (function($) { do some stuff } )(jQuery);
>
>

Reply via email to