javascriptjqueryiife

In Javascript, what does this syntax mean?


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 () {
    ...
}()); 

Solution

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