I'm writing a javascript for my webpage, and was wondering what is the difference between document.addEventListener() and this.addEventListener()? Both work for me, but is there any performance impact between the both options?
e.g.
Option 1:
class SomeThing {
constructor() {
this.my_button = document.getElementById("id-1")
this.events();
}
events() {
this.my_button.addEventListener("click", () => {
console.log("Button clicked");
});
}
}
export default SomeThing;
Option 2:
class SomeThing {
constructor() {
this.events();
}
events() {
document.getElementById("id-1").addEventListener("click", () => {
console.log("Button clicked");
});
}
}
export default SomeThing ; Which option is better and correct, and why? Thanks
CodePudding user response:
Unless you're in the very, very strange of an extremely tight loop around this, the performance considerations of looking up a element by ID will be completely irrelevant.
What you would need to watch out for is that, if you use this
, that the this
context is always correct. If it isn't, you'll run into errors and your app won't function. For example, if you tried to do
const s = new SomeThing();
someButton.addEventListener('click', s.events);
it wouldn't work, because your current first implementation of events
requires a this
of the SomeThing
instance.
If that's something you might be worried about, change
events() {
this.my_button.addEventListener("click", () => {
to
events = () => {
this.my_button.addEventListener("click", () => {
Otherwise, whether or not you use this
or retrieve the element inside the method is more of a style preference than anything else. Better to optimize for readability and maintainability first. (which may imply - if the button gets used elsewhere, better to select it once, then use that reference everywhere, rather than to select it everywhere it gets used, which would require a bit of WET code that could be annoying to refactor if you found that you needed to change the selector needed to select the button.)