Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Jul 2011
    Posts
    172
    Thanks
    64
    Thanked 2 Times in 2 Posts

    Calling a function - with or without brackets / either way?

    Code:
    <form>
    <input type="button" value="Click!" id="001" />
    </form>
    
    function one() {
    window.alert('Hello');
    window.alert('World!');
    }
    
    var varname=document.getElementById("001");
    varname.onclick=one;
    I am not sure if the last line is this example is correct. Should it not be:

    varname.onclick=one();

    Or is it ok to write it either way?
    Thanks.
    Last edited by joliett89; 10-05-2011 at 04:13 PM.

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,082
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    No, the meaning is quite different.

    To call (use, execute, invoke) the function you must include the () brackets.
    If you omit the brackets, you don't actually call the function. Instead you get a reference to the function object. (Whenever you use a function name without parentheses, it acts like a regular variable).

    Code:
    <script type = "text/javascript">
    
    function a() {
    alert ("Hello World");
    }
    
    a();
    
    var x = a;
    alert (x);
    
    </script>
    You should not delete your posts as they may be of value to someone else. Also as a courtesy to anyone who has troubled to answer them.

    "When I was a kid I used to pray every night for a new bike. Then I realised that The Lord doesn't work that way, so I stole one and asked him to forgive me."
    Last edited by Philip M; 10-05-2011 at 02:59 PM. Reason: Added example

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    joliett89 (10-05-2011)


  •  

    Posting Permissions

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