`this` is undefined inside a callback/event handler
Locate the failed assumption, reproduce it, then repair the cause.
What actually caused it
A regular received a different from the one you expected. A call such as counter.read() supplies counter as this, but copying counter.read into a callback variable does not preserve that call form.
In a strict-mode plain call, this is . A browser timer or a listener may supply another instead: a regular DOM event listener normally receives its current element. Either way, the original application object is not automatically retained.
Arrow use the surrounding this instead of a call-time . An arrow created at top level therefore does not magically point to an object whose property later stores it. The actual runtime error may mention reading a property of undefined rather than mentioning this itself.
Minimal reproduction
A detached method in strict mode
"use strict";
const counter = {
value: 3,
read() { return this.value; }
};
const callback = counter.read;
console.log(callback());The fix
When the should retain a 's , use bind once and keep the returned function, or wrap the call in an arrow that explicitly invokes the method on its object. An arrow created inside a correctly called method can also retain that method's this.
For listener cleanup, save the bound or arrow so removal uses the same identity. If you intended the element instead, use event.currentTarget explicitly; that states the event relationship without depending on a surrounding 's this.
Bind the intended receiver
const counter = { value: 3, read() { return this.value; } };
const callback = counter.read.bind(counter);
console.log(callback());Keep the method call in an arrow
const counter = { value: 3, read() { return this.value; } };
const callback = () => counter.read();
console.log(callback());