Is there any reason to use an ID vs "this" in the following examples:
$("#firstname").click(function() {
$("#firstname").val("changed");
});
vs:
$("#firstname").click(function() {
$(this).val("changed");
});
Outcome is the same either way.
The idea is that if you change firstname above, you won't have to change it again in the second block. Eg:
$("#my-new-name").click(function() {
// "this" remains the same.
$(this).val("changed");
});
Also, performance-wise, jQuery will not need to parse the string and run through its selector engine, and instead this is a raw DOMElement that it can quickly detect its type and get on its way.
One reason to use this rather than the id is performance.
When you enter the click handler, this already exists and is set.
Therefore, I imagine it is much faster to create a jQuery object with this rather than invoking sizzle, the selector engine, to find that element by id and create the jQuery object
Another reason for choosing this is semantics. Semantically, this is easier to read in context when I enter the click handler. This is because I already know that the handler is for #firstname. However, if I see an id selector, I have to double check and make sure both the handler selector and the id selector are one and the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With