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

Some jQuery methods expect a function as a parameter, but to work, they must receive an anonymous function as a parameter, not a function directly, as in the following example:

$("a").on("click", function () { retornaNada(); }); 

but not

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

Consider retornaNada() as a function without any code. Why can't we pass the function directly?

+6
source share
1 answer

It works, but you only need to pass a link to the function (name) as follows:

 function test (e) { console.log('test ok'); } $('body').on('click', test); 
+5
source

All Articles