views:

58

answers:

2

Possible Duplicate:
Location of parenthesis for auto-executing anonymous JavaScript functions?

Question is a duplicate of http://stackoverflow.com/questions/3384504/location-of-parenthesis-for-auto-executing-anonymous-javascript-functions and http://stackoverflow.com/questions/440739/what-do-parentheses-surrounding-a-javascript-object-function-class-declaration-me

Just curious really, what are the purposes of the brackets in this code:

(function() {})();

This looks like I could just as easily write:

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

With jQuery plugins we would do something like...

(function($) {})(jQuery);

What's the deal with the brackets?

+2  A: 

With the parentheses (surrounding the function), you don't have to declare a name, littering the namespace. And, they serve to alert readers of your code to the fact that you're using a self-invoking function.

The second set of parentheses actually invoke/call the (anonymous) function you just created. Since Javascript functions are actually just variables (or "first-class objects" in CS-speak), you've just created a variable (in the first set of parentheses), which you call using the second set.

Here's an example:

function callFunc(f) {
    return f("test");
}

callFunc(alert);

In the example, f actually references the function alert, which you call in the function code with the parentheses.

palswim
Why do I almost always see a set of brackets right after the part that encapsulates the function? Did you happen to know the ecma section that describes this behavior?
@user257493: those parentheses actually invoke the function.
Daniel
as a note: one parenthesis, two parentheses.
Peter Ajtai
+1  A: 

In case of the jQuery example you define an anonymous function that takes a parameter called $ and then pass the jQuery object to it. It will stay inside that scope and not conflict with other frameworks that have $ globally defined.

Other than that, personally it looks cleaner to me.

Daniel
I'm not really concerned with what the jQuery plugin code does as much as I am the purposes of the brackets.
That's more the reason for enclosing the code in a function, and not so much a reason for the parentheses themselves.
palswim