I have following code:
let myObj = {
foo: "bar",
getFoo: function() {
console.log(this.foo);
},
method: function() {
if (true) {
window.addEventListener('scroll', this.getFoo);
} else {
window.removeEventListener('scroll', this.getFoo);
}
}
}
window.addEventListener('click', () => {
myObj.method();
});
It returns undefinded, since (for reasons unknown to me) this
refers to the window
object if getFoo
is called as a callback in an addEventListener
function.
Now if I used an arrow function inside myObj.method
-
window.addEventListener('scroll', () => {
this.getFoo();
});
This would work, but then I called an anonymous function and can't do removeEventListener
later.
How could I get this working with a non-anonymous function?