views:

110

answers:

3

I found this snippet when i was looking at jQuery plugins and wonder what it actually does

A jQuery plugin skeleton:

(function($) {
    ... 
})(jQuery); 

And more recently in nettuts:

var STICKIES = (function () {
    ...
}()); 
A: 

The first part:

function($) {
    ... 
}

creates an anonymous function. The second part: wrapping this function with braces and (jQuery); cal the function with jQuery as argument (usable via $ in the function).

nettuts then saves the result of the call in the variable.

alopix
A: 

The first function means that $ is overwritten by jQuery, which is useful if you have given a different meaning to '$' in the script.

Jan-Frederik Carl
+7  A: 

This creates a anonymous function and calls it directly: this is equivalent to

var fun = function(){};
fun();

its used in jquery plugins to ensure compatibility with other libraries defining a global variable '$'. in your plugin sekeleton, you wrap your plugin in a anonymous function, which receives an argument named '$' (thus overriding a global variable '$'), this anonymous function is then called with 'jQuery' as parameter, so effectively $ becomes = jQuery, but only within that anonymous function.

Cice
+1 for explaining the reason this is done
Nicolas78