4

Possible Duplicate:
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

I have stumbled upon many times this unusual way of coding, and it seems to be becoming popular.

(function (variable) {
    // properties or methods go here

    // some more stuff
})(variable)

It's hard for me to even research it, because i don't even know how it's called. i have worked with it with jquery with but i still don't know how it works.

example:

(function ($) {
    ...
        // code to manipulate the dom
    function init() {
        .....
        }

    $(document).ready(function () {
        init();
    });
})(jQuery);

I've only used it because i was updating some code made by another developer.

Is there any advantage to coding like this? Is there a place where i can read more about it? If anybody understand my question, it will be nice to see some articles that talk about this, or maybe you have some insight on how to make your own.

Thank You

Ibu

Community
  • 1
  • 1
Ibu
  • 42,752
  • 13
  • 76
  • 103
  • I understand it might be a duplicate but i couldn't find anything on stack overflow cause i don't know how it is called – Ibu May 12 '11 at 17:23
  • No worries, but the question I linked to has your answer. – Vivin Paliath May 12 '11 at 17:24
  • please correct your example, you usually use an anonymous function with jquery to ensure that in a certain scope an exact version of jquery is used, and your function doesn't accept any parameter. Add $ as parameter – Riccardo Galli May 12 '11 at 17:27

1 Answers1

2

Its called a self invoking anonymous function. Look at this thread for more details about how it works and why its used,

Why do you need to invoke an anonymous function on the same line?

Community
  • 1
  • 1
Aravindan R
  • 3,084
  • 1
  • 28
  • 44