What's the difference between a function pointer and a function call?

Hi,
I’m working through the sitepoint ajax book and had a problem with a particular chunk of code. I eventually tracked down the error and it was being caused because I had:

window.onload = Monitor.init();

instead of:

window.onload = Monitor.init;

Now, one of the sticky threads mentioned that the first is a function call and the second is a function pointer. My questions are:

  1. What’s the difference between a function call and a function pointer?
  2. Why did it cause problems in this particular case?
  3. What are the general implications/issues with using one over the other?

Regards,
Duncan

A function call is when you call a function and the code within it is executed.

A function pointer (also known as a function reference or a callback) is a reference to the function. In the case of a pointer though, no code is executed.

In this case it caused a problem because you were setting window.onload to the return value of Monitor.init() (which was likely null). Also when you did this, the code of your function was executed prematurely at that line, instead of when the window loaded as intended.

When it was set up properly, you were essentially telling it to call the function Monitor.init() when the window loaded (and everything else was loaded and ready to go).

Take for example this function:


function pageIsLoaded() {
  alert("Page has loaded");
}

If I then do this:


window.onload = pageIsLoaded();

the alert will pop up as soon as that line of Javascript is loaded. Since my function has no return value, window.onload is set to null, and thus does nothing when the page actually loads.

In contrast, if I do:


window.onload = pageIsLoaded;

it does nothing at that line except tells window to call the function pageIsLoaded when it finishes loading. When it finishes loading, it’ll then call the function, causes the alert to be shown.

Make sense?