First thing to consider is that in Javascript functions are first class objects, which means that they can be assigned to variables and passed as argument to other functions in the same way as you would with a string or a number or an array or etc...
So it’s perfectly natural to do something like this:
var minhaFuncao = function( mensagem ) {
console.log( mensagem );
};
// ou...
var minhaOutraFuncao = funcaoQueFazAlgumaCoisa;
function funcaoQueFazAlgumaCoisa( mensagem ) { console.log( mensagem ); }
And then that:
minhaFuncao( "Chamando minhaFunção!" );
// ou...
minhaOutraFuncao( "Chamando minhaOutraFuncao" );
// ou...
funcaoQueFazAlgumaCoisa( "Chamando funcaoQueFazAlgumaCoisa" );
With that in mind, consider the following function:
function passeMeUmaFuncaoQualquer( mensagem, umaFuncaoQualquer ) {
umaFuncaoQualquer( mensagem );
}
The above function expects to receive as first argument a string and as second a function, then we could invoke it as follows:
passeMeUmaFuncaoQualquer( "Olá, Mundo!!!", function( msg ) { console.log( msg ) } );
// ou...
function umaFuncaoQualquer( msg ) {
console.log( msg );
}
passeMeUmaFuncaoQualquer( "Olá, Mundo!!!", umaFuncaoQualquer );
And if I do it:
passeMeUmaFuncaoQualquer( "Olá", "Mundo" );
It will make a mistake, because it would be the same thing to do:
"Mundo"();
And you can’t invoke a string, it’s not even?
Now, if I do it the way you showed me:
passeMeUmaFuncaoQualquer( "Olá, Mundo!!!", umaFuncaoQualquer() );
What happens is I summoning umaFuncaoQualquer
and passing the value returned by it (whatever it may be) as the second argument of passeMeUmaFuncaoQualquer
, which creates an error.
It’s just an example to learn even kkk functionality
– Jhuan Marco