running function in class error

Hey, in the code below, the example function won't run and it gives the error "Uncaught TypeError: this.example is not a function". I'm a little confused as to why this is happening, could someone point me in the right direction? Thanks in advance.
class Button {
constructor() {}

addEventListener() {
document.getElementById("button").addEventListener("click", this.handleClick);
}
handleClick() {
this.example()
}
example() {
console.log("hi") // I won't run
}
}

let button = new Button();
button.addEventListener()
class Button {
constructor() {}

addEventListener() {
document.getElementById("button").addEventListener("click", this.handleClick);
}
handleClick() {
this.example()
}
example() {
console.log("hi") // I won't run
}
}

let button = new Button();
button.addEventListener()
3 Replies
ἔρως
ἔρως2mo ago
that's because the this changes for the event listener you need to use an arrow function
document.getElementById("button").addEventListener("click", () => this.handleClick);
document.getElementById("button").addEventListener("click", () => this.handleClick);
and we've explained before, arrow functions don't change the this value
snxxwyy
snxxwyyOP2mo ago
oh right of course, that didn't even come to mind at the time haha, i thought it was something class related, thanks epic
ἔρως
ἔρως2mo ago
you're welcome
Want results from more Discord servers?
Add your server