Weird Javascript syntax..

We encourage users to post events happening in the community to the community events group on https://www.drupal.org.
tjholowaychuk's picture

Other than this there isnt really much that strikes me as being overly weird about javascript but I cannot find any good documentation on this syntax that I have seen around because I dont know what it does! Any suggestions or documentation would be great thanks, its just been bugging me...

(function() {
    // ...
})();

(function() {
    // ...
})(var);

function() {
    // ...
})();

Comments

Anonymous function

recidive's picture

The code:

(function() {
  // ...
})();

is similar to:

var x = function() {
  // ...
};

x();

it is, an anonymous function that call itself after declaration. The difference is that you don't clutter the global namespace on the first example.

This is usually used in jQuery extensions where people do the most they can to keep code small, avoiding conflicts with other libraries that declare '$'. E.g.:

$.x = function() {
  $('.class').something();
};

Would conflict with other libraries such as prototype. While:

jQuery.x = function() {
  jQuery('.class').something();
};

wouldn't. But when file size becomes a problem, i.e. to many calls to jQuery (6 chars instead of one: '$'), people do:

(function($) {

$.x = function() {
  $('.class').something();
}

})(jQuery);

so they can use '$' whenever they want inside the anonymous function being sure it will always refer to the jQuery object.

ah ! i see! it makes sense

tjholowaychuk's picture

ah ! i see! it makes sense now, thanks for that, makes perfect sense