On Jul 28, 5:53 am, James <james.gp....@gmail.com> wrote:
> This:
> (function() { do some stuff } )();
>
> is known as a closure.

You have a warped view of a closure. It is an example of the module
pattern, which can create closures, but doesn't necessarily do so.

URL: http://www.jibbering.com/faq/faq_notes/closures.html >

> 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).

More or less.


> Compared to this:
> function doSomething() { // do some stuff };
>
> The doSomething variable will exist (globally) to be available for
> access again.

There are many ways to created global variables, declaring a function
in the global scope is one.

> 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.

Maybe. There are other methods for avoiding name collisions.


> 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.

There is no closure unless "do some stuff" creates one (which would
require a function declaration or expression inside the anonymous
function at least). It is the fact that $ is created as a local
variable and assigned a reference to the jQuery function that
"protects" it from collisions outside the function.


--
Rob

Reply via email to