1

Possible Duplicate:
What does this “(function(){});”, a function inside brackets, mean in javascript?
javascript anonymous function

(function())()

this is used in many js library like jquery,YUi

Community
  • 1
  • 1
Bhavik Patel
  • 21
  • 1
  • 6

5 Answers5

5

Thats called Module Pattern. The idea is to have an encapsulated module, that cannot conflict with any other modules you or someone else has created. You can create public and private methods within that module. See: Js Pattern

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
  • Moreover, it immediately executes the content of what is inside, without letting any traces in the global variable space (unless it is populated by adding objects in the window global object). – Vincent Hiribarren Mar 19 '12 at 06:32
4

I'm not sure what (function())() means, but I'll work on the assumption that you meant (function() { … })(). It is roughly the same as:

f = function() { … }; // Define a function.
f();                  // Call it.

The only difference is that it does so without requiring a variable.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
1

It is an anonymous self executing function. It is anonymous, because it is not named, and self executing, so it runs (there would be no other way to run an un-named function).

It is particularly useful to enclose a discreet module of code, because it acts as a closure preventing variables leaking into the global namespace.

Billy Moon
  • 57,113
  • 24
  • 136
  • 237
  • means this function will be called after page has been fully loaded? – Bhavik Patel Mar 19 '12 at 06:34
  • 1
    No, it will be executed immediately. It looks similar to the format used in jQuery (or other tools) to execute after the page is loaded. Also, jQuery plugins use that pattern to encapsulate the module. – Billy Moon Mar 19 '12 at 06:47
0

You're immediately calling an anonymus function with a specific parameter.

An example:

(function(name){   alert(name); })('peter') This alerts "peter".

In the case of jQuery you might pass jQuery as a parameter and use $ in your function. So you can still use jQuery in noConflict-mode but use the handy $:

jQuery.noConflict() (function($){   var obj = $('<div/>', { id: 'someId' }); })(jQuery)
Kishore Kumar
  • 12,675
  • 27
  • 97
  • 154
0

It simply executes the code wrapped in parentheses right away (the first block returns a function, the second pair of parens executes it).

Take for instance these two snippets:

function foo() {
    print 'foo';
}

(function() {
    print 'foo';
})();

The first won't do anything until you call foo(); whereas the second will print 'foo' right away.

Kit Grose
  • 1,792
  • 16
  • 16