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.

0 Comments:

Post a Comment

<< Home