SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Jan 2007
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question 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

  2. #2
    SitePoint Wizard
    Join Date
    Dec 2003
    Location
    USA
    Posts
    2,582
    Mentioned
    29 Post(s)
    Tagged
    0 Thread(s)
    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:
    Code:
    function pageIsLoaded() {
      alert("Page has loaded");
    }
    If I then do this:
    Code:
    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:
    Code:
    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?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •