views:

77

answers:

2

I have recently started to delve deeper in to JavaScript and have come across this code construct in JQuery.

(function( window, undefined ) {
})(window)

Reading on stack overflow (and elsewhere) I have come to the conclusion that this is the same as

function foo(window, undefined) {
    ...
}

foo(window);

Am I correct in my assumption? If so, what are the advantages of the former? (other than confusing newbs)

+1  A: 

This is an anonymous function. It is created and then goes out of scope, which here is the advantage. It is created and instantiated immediately. What is good about this is that it is not going to collide with any function on the global namespace, and thus will not obliterate anything you may have included on the page.

Scott
That makes sense, especially when combined with the link in the answer below and seeing the last few lines in jquery in that context.
Elija
A: 

It is an anonymous function, it has quite a few benefits, like being only active in the current scope. You can read more about it here.

Ólafur Waage