PDA

View Full Version : Functions in parentheses



brettz9
06-06-2005, 04:36 PM
Hello,

I am new to Javascript, so please bear with me.

I was examining the bookmarklet "Sort Tables" here (http://www.squarefree.com/bookmarklets/pagedata.html) and it contained a function ITSELF enclosed in pareentheses:



(function(){
var j, thead;
for(j=0;j<g_tables.length;++j){
thead=g_tables[j].createTHead();
insAtTop(thead, makeHeader(j,countCols(g_tables[j])))
}
}) ();


As this script did not work with the parentheses removed, I am wondering what this does. Please note: I am referring to the function declaration being itself enclosed not the arguments passed to it.

thanks,
Brett

Chroder
06-06-2005, 07:53 PM
In this case, the function is a closure (aka 'inline function' aka 'anonymous function').

A function in Javascript is just another type of value. The parenthesis just make the function act as a value, which is then executed (as per the familiar '()' at the end).

For example, you could assign a function to a variable and then call it:
myFunc = function() { .... code .... };
myFunc();
Or just stick parenthesis around it and execute it as an inline "value":

(function() { .... code ....})();

brettz9
06-07-2005, 12:54 AM
Wonderful, thanks!

I had seen online information about anonymous functions, but I hadn't seen them with outer parentheses...What you said makes sense...

It threw me off because it wasn't an argument to another function.

best wishes,
Brett