#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    10
    Rep Power
    0

    Event/Callback Question


    I've come seeking help because I am extremely confused. I'm a newbie programmer learning JS so bear with me.

    Code:
    window.onload = function() {
    document.getElementById("someId").onclick = someDeclaredFunction();
    }
    I don't understand why someDeclaredFunction() won't work as the callback? Yet wrapping/writing it in an anonymous function works fine e.g.
    Code:
    function() { someDeclaredFunction(); }
    I thought the only difference between function declarations and function expressions were the way they are loaded. Also that anonymous/named is basically just semantics.

    If anyone could take the time to explain this to me I would be extremely grateful.
  2. #2
  3. No Profile Picture
    Lost in code
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 2004
    Posts
    8,317
    Rep Power
    7170
    The expression:
    someDeclaredFunction();
    Executes the function someDeclaredFunction immediately. The expression's value is whatever is returned by the call to someDeclaredFunction.

    The expression:
    function() { someDeclaredFunction(); }
    Declares an anonymous function; when that anonymous function is run, someDeclaredFunction is executed. The expression's value is a reference to the anonymous function.

    If you removed the () from the first expression, then the expression value would be a reference to the function instead.
    PHP FAQ

    Originally Posted by Spad
    Ah USB, the only rectangular connector where you have to make 3 attempts before you get it the right way around
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    10
    Rep Power
    0
    If you removed the () from the first expression, then the expression value would be a reference to the function instead.
    Oh my God. Facepalm. Haha thank you man.

IMN logo majestic logo threadwatch logo seochat tools logo