SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    SitePoint Addict
    Join Date
    May 2007
    Posts
    242
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    About Function calls

    Hello. I am a bit confused about function calls. Why dont we use parentheses when we call the other functions as a method of the object, e.g when creating event handlers?

    PHP Code:
    document.getElementById("toolbox").onclick=serto
    And why we do use parentheses when calling the function as the attribute value?

    PHP Code:
    <div id="toolbox" onclick="serto();">

    </
    div
    In short I wish to learn how to call functions the right way?

    Thanks in advance.

  2. #2
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,158
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    When you use the onclick property, you assign a function reference; a 'pointer' to the function to be called when the even occurs. You could do something like this,
    Code JavaScript:
    document.getElementById("toolbox").onclick=serto();
    provided that the call to serto() returned a function reference. E.g.,
    Code JavaScript:
    function serto() {
      return function() { /* do something */ }
    }

    When you use an event attribute in HTML, like this,
    Code HTML4Strict:
    <div id="toolbox" onclick="serto();">
    you are doing the equivalent of this,
    Code JavaScript:
    document.getElementById("toolbox").onclick = function() {
      serto();
    }

    A major difference between the two methods is what the this keyword refers to in the called function. In the first case, this refers to the HTML Element object with ID 'toolbox'. In the second case, this refers to the global object (or window object) inside the serto function.
    Birnam wood is come to Dunsinane


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
  •