Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

rather than

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

Consider retornaNada() as a function without any body of code. Why can not we pass the function directly?

like image 583
Philippe Gioseffi Avatar asked Feb 03 '14 16:02

Philippe Gioseffi


1 Answers

It's working but you need to pass only the function reference (name) like this :

function test (e) {
    console.log('test ok');
}
$('body').on('click', test);
like image 200
Goran.it Avatar answered Oct 25 '22 00:10

Goran.it