Why should we use anonymous functions with jQuery instead of the function directly?


I have a doubt, some jQuery methods expect a function as a parameter, but to work they should receive an inner function as a 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 of any type without a code body. Why can not we pass the function directly?

asked by anonymous 03.02.2014 / 16:59

2 answers


Methods that expect a function expect a reference function. For example:

$("a").on("click", retornaNada); 

This is advantageous if you want to use the same function as event handler in more than one place. For example:

$("a").on("click", retornaNada); 
$("span").on("click", retornaNada); 

Passing anonymous functions would require two different functions.

Now notice that what you did was:

$("a").on("click", retornaNada()); 
//                  ----------^^

You called the function, and actually passed the return value as the handler. As retornaNada does not return anything, including the parentheses means the same as:

$("a").on("click", undefined);

So it does not work.

03.02.2014 / 17:12

You can only send the function name. for example: You declare the function that will handle the event before:

function meuOnClick() {

And then it makes your jquery point to it:

$("a").on("click", meuOnClick);

Note that it is without parentheses. However, this is kinda bad, because you will not be able to use the jquery selectors, such as $ (this). The normal thing is to use an anonymous function.

03.02.2014 / 17:07