6

I have a function called showText() which copies some text from form textbox to a paragraph elsewhere. It is called with the following:

document.getElementById("mybutton").onclick = showText; 

It will not work if I add the () to the end of showText, which I understand from reading similar answers here is the only way to call a function.

Later in the script it requires the () to work:

window.addEventListener("keypress", function(e) {
    var keycode = e.keyCode;
    if (keycode == 13) {
        showText();
    }
}, false);

I'm not sure what is going on here.

yuriy636
  • 11,171
  • 5
  • 37
  • 42
Russell
  • 655
  • 2
  • 9
  • 21
  • Functions are objects. Your two examples illustrate assignment of the function vs calling the function. –  Apr 02 '13 at 22:26

3 Answers3

16

showText returns the function showText.

showText() runs the function showText and returns the result.

When you attach a function to an event handler like .onclick, it is expecting a function.

You can call a function and return the result to an event like this: document.getElementById("mybutton").onclick = showText(); provided the function itself returns a function:

function showText() {
    return function () { 
        alert('hello world'); 
    }
}
Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
0

In Javascript functions are first class citizens which means they can be assigned to a variable ... that is what you are doing i the first one ... You are basically setting the onclick to a function of your choice (telling the browser that when this is clicked ... call this function)

By using () you are calling the function ..

I can also do something like this

function test() {
  alert('Alert something');
}

var a = test;
a();
jsshah
  • 1,741
  • 1
  • 10
  • 18
0

When you have a statement like:

onclick = showText;

the right hand side expression is evaluated and the result assigned to the left hand side. If the identifier showText resolves to a function object, a reference to that object is assigned.

If showText is followed by a formal parameter list enclosed in brackets, i.e. showText(), then the function is called with the supplied parameters and the result is assigned. The formal parameter list can be empty.

RobG
  • 142,382
  • 31
  • 172
  • 209