The biggest difference I see is in the statements.
In option 1, you used a function, and in option 2, an anonymous function.
I think the main difference in this case is that, with the function declared, and then passed by callback
, you can repeat it for different events (as many times as you like) without repeating unnecessary code.
Example:
$('#dois').on("click", testar);
$(document).on("click", ".botao-dinamico", testar);
function testar() {
console.log('Teste Dois');
}
As already mentioned, many people do not know that it is possible to do this operation in jQuery and end up falling into the following problem:
$('#dois').on("click", function () {
console.log('Teste Dois');
});
$(document).on("click", ".botao-dinamico", function () {
console.log('Teste Dois');
});
Note that the second example is an unnecessary complication . So I get my first choice.
Of course we have to remember that the example is very simple in this case. You could have greater gains in cases where you needed a more complex function.
For example, your testar
q function could be using this
or some specific parameters (like event
) normally, because in the end this will not make any difference, since everything jQuery needs is a callback.
Bonus
If you just want to consider the following information as a curiosity, you can still use an anonymous function named:
$('#um').on("click", function onClick() {
console.log(onClick);
});
In the specific case, it will not go into the global or local scope of Javascript, but will be accessible only from the anonymous function itself.