Why you need to create a number or a string or a array, or any other object? Why does the problem ask for that, right? It’s the same thing. You have a problem that requires a function, so you have to create it.
In this specific case you have a property of an object that is an event, that is, when something happens to the object it must perform something. How to tell her what to execute? You create a function with which to execute and inform what this function is for the property, just as you do with any other value. The function is just a value. Its value is the code to be executed.
The syntax
.onclick = myFunction()
Is calling the function myFunction()
and putting the result of it in .onclick
, is not what you want, you do not want the result of the function, you want the function itself.
Already the syntax
.onclick = function() {myFunction()};
It does not call the function, it just declares the function and the function itself is stored in .onclick
. In case this anonymous function (note that it does not have a name) just calls myFunction()
.
This technique is called callback, that is, you are saying what should be called back at a certain time.
The different syntax defines whether you are calling or creating a function. The function statement always starts with the reserved word function
and always has a body, may or may not have a name.
This:
function nome() {}
is the same as this:
nome = function() {}
A simplified way of doing the same:
.onclick = myFunction
Note that the syntax here is not a function call because it does not include parentheses. So you’re just passing the name of an existing function instead of calling the function. So think like this:
nome = function() {};
.onclick = nome;
Look, you’re declaring a function and you’re holding it in a variable. Here you’re taking the value of this variable, which is a function, and you’re assigning it to the property .onclick
. It’s the same as doing:
function nome() {}
.onclick = nome;
But this is a little different:
function nome() {}
.onclick = function() {nome()};
Cstamped on Github for future reference.
Because here you have two functions One that calls to the other.
The first example could be just
.onclick = myFunction
and so it would be very easy to see the difference.– Woss
You have to create an id for your input, after all you are sending your function to capture by the ID "demo" you understand
– Victor