Wednesday, July 16, 2008

Function reference vs. function call

Here's a JavaScript function definition:
function foo() {
  alert('foo!');
}
You can refer to that function like this:
foo
And here is how to call (execute) the function:
foo()
Even experienced developers new to JS tend to get these confused. For example, jQuery's getJSON method allows you to specify a function to be executed once the operation is complete. Be careful not to plug in the function call when what you really need is a function reference:
$.getJSON( "action.php", {data:'some data here'}, foo() );
This will execute the foo function instantly. Not what you want. So leave off the parens:
$.getJSON( "action.php", {data:'some data here'}, foo );
This merely passes a reference to the function. It won't execute until it's called by jQuery.

4 Comments:

At 6:15 AM, Blogger Nick said...

Also known as a Functor... for C and C++ users anyway.

 
At 9:58 AM, Blogger Justin said...

In C you only have function pointers, not function objects.

 
At 3:21 PM, Blogger Curious said...

What if I want to pass an argument in foo?

 
At 12:56 PM, Blogger Braden said...

@Curious, did you ever find an answer? I'm also wondering how to pass arguments to foo

 

Post a Comment

<< Home