Bind a context to the event listener (JS/TS)
Class { var = 3 Func {
element.addEventListener("click", this.handler())
} handler(event:Event){
console.log(this.var)
}}
In this case, if you use the ‘this’ keyword in the listener, that works differently.
there is no more the var in the ‘this’. in the event handler, ‘this’ means ‘event.target’. So you cannot retrieve the ‘var = 3’ value. if you want, you can use the ‘bind()’ method.
Class {var = 3Func {
element.addEventListener("click", this.handler().bind(this))
}handler(event:Event){
console.log(this.var)
}}
And then, ‘this.var’ will work as you’d expected.