Function reference vs. function call
Here's a JavaScript function definition:
function foo() { alert('foo!'); }You can refer to that function like this:
fooAnd 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:
Also known as a Functor... for C and C++ users anyway.
In C you only have function pointers, not function objects.
What if I want to pass an argument in foo?
@Curious, did you ever find an answer? I'm also wondering how to pass arguments to foo
Post a Comment
<< Home