Why do you need to create a number or a string or an array , or any other object? Why the problem asks 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 execute something. How to tell her what should be done? You create a function with what to run and tell you what that function is for the property, just like you do with any other value. The function is only a value. Its value is the code to run.
The syntax
.onclick = myFunction()
You are calling the function myFunction()
and putting the result of it in .onclick
, is not what you want, does not want the result of the function, you want the function itself.
The syntax
.onclick = function() {myFunction()};
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) only calls myFunction()
.
This technique is called callback , that is, you are saying the which should be called back at a given time.
The different syntax defines whether you are calling or creating a function. The function declaration 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 to do 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;
Looks you are declaring a function and you are saving it to a variable. Then you're getting the value of this variable, which is a function, and is assigning it to the .onclick
property. It's the same thing to do:
function nome() {}
.onclick = nome;
But this is a little different:
function nome() {}
.onclick = function() {nome()};
Because here you have two functions one that calls the other.