简体   繁体   中英

What is the Difference between function and function() When I call them in javascript?

I had a question before and a person answered it very well, My code works now, But I didn't completely understand the answer. This is the coding bit that I didn't understand -

document.getElementById("myButton").onclick = words;

Now I already had defined function words(). My mistake was that I had written words() instead of words. So what is the difference between calling of words() and words ?

words evaluates as a function.

words() calls that function and evaluates as the resulting return value.


The value you assign to onclick needs to be the function you want to get called when the click happens.

If you want the words function to be called, you have to assign that.

The difference between words and words() is that in the first case you are referencing the function and in the second case you are calling it

so when you do

document.getElementById("myButton").onclick = words;

you are assigning a function words to the onclick listener, while if you do

 document.getElementById("myButton").onclick = words();

you are actually assigning the evaluated value of words to the onclick listener. onclick needs to be assigned a function which will be called when an onclick event happens.

Doing:

document.getElementById("myButton").onclick = words;

this means:

put a pointer to the function and when the event fires it will call the function. When you do words() you call the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM