20
I have a question, some methods of jQuery expect a function as parameter, but to work they must receive an Inner Function as parameter instead of a function directly, as in the example below:
$("a").on("click", function() { retornaNada(); });
instead of
$("a").on("click", retornaNada());
Consider retornaNada()
as a function any type without code body. Why can’t we pass the function directly?
Now I understand the problem, actually the expected parameter is not a function but a reference to a function. Even if
retornaNada()
wereretornaUm() { return 1; }
the problem would be the same, right?– Philippe Gioseffi
Exactly! Now, if it were
function retornaFunc() { return function(){ console.log(this) };}
would work, and the clicked element would be logged in to the console. Because then you would be returning a function.– bfavaretto
yes @Philippegioseffi the problem would be the same, because javascript can store functions in variables that would be closures, where you would be passing the command to execute it instead of passing the reference itself. Study closures[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures] that you will understand everything you need to know about this. :)
– Paulo Roberto Rosa
@Pauloroberto, thanks for the link, I will read carefully.
– Philippe Gioseffi
@bfavaretto understood your example, now in the matter of performance is it better to use with reference to the function or Anonymous Function? And another how to pass arguments to the function in both cases?
– Philippe Gioseffi
@Philippegioseffi There is no practical difference in performance. Only if you place the same event in multiple elements (with multiple calls to
.on
) you save memory if you always pass a reference to the same function. On passing arguments, deserves a separate question, the answer will not fit in a comment :)– bfavaretto
@bfavaretto Thanks for the reply on performance. I will create the second question then.
– Philippe Gioseffi
@bfavaretto Follows the question: How to pass parameters in function calls by reference in Javascript?.
– Philippe Gioseffi