I'm writing a class named Graph using JavaScript. Code is like following:
export default class Graph {
constructor(props) {
document.querySelector('#slider').addEventListener('change', function (){
// Uncaught ReferenceError: fun is not defined
this.fun()
})
}
fun () {
// some code
}
}
Of course, code like this can't work.Since in the callback function, 'this' only points to the slider.Browser also complained about reference error after I deleted 'this'. Is there some method to fix this problem?
CodePudding user response:
You can use an arrow function which will capture the right value of this, but careful with memory leak, if your object Graph has a limited lifetime you have to think about clearing the event listener. You can use the event argument to target your slider.
export default class Graph {
constructor(props) {
this.onchange = event => {
this fun();
console.log(event.currentTarget);
}; // reference the callback in order to be able to clear it later.
document.getElementById("slider")
.addEventListener("change", this.onchange);
}
clear() {
document.getElementById("slider")
.removeEventListener("change", this.onchange);
}
fun() { // some code }
}