The biggest difference I see is in the statements.
In option 1, you used a function, and in option 2, an anonymous function.
I believe the main difference in this case is that, with the stated function, it is then passed by callback
, you can repeat it for different events (as many times as you want), 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 such an 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 a unnecessary complication. So I get my first option.
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, its function testar
could be using this
or some specific parameters (such as event
) usually, because in the end it won’t make any difference, since all jQuery needs is a callback.
Bonus
If you just want to consider as a curiosity this information that I will pass on, it is still possible to use an anonymous named function:
$('#um').on("click", function onClick() {
console.log(onClick);
});
In the specific case, it will not enter the global or local scope of Javascript, but will only be accessible from the anonymous function itself.
I think not, because in jquery the second parameter is a call to a function. So do
$('#dois').on("click", testar);
would be the same as$('#dois').on("click", function(){ //... } );
– Mauro Alexandre