Why does this get lost in class method callbacks in JavaScript?
Because the method is detached from the instance when passed as a reference. The callback is called as a plain function, so this is not the instance. Fix by binding in the constructor or using arrow class fields.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in this in ES6 Classes in JavaScript
this in the constructor is the new instance. this in methods is the instance when called as instance.method(). But detaching a method (passing to setTimeout or addEventListener) loses this. Fix with bind, arrow class fields, or arrow wrappers.
Three ways: bind in the constructor (this.handleClick = this.handleClick.bind(this)), use arrow class fields (handleClick = () => { ... }), or use arrow wrappers in callbacks (setTimeout(() => this.method(), 1000)).
Class fields defined as arrows (handleClick = () => { ... }). They capture this from the constructor's scope (the instance), so they are always bound. They are per-instance (not on the prototype), so they cost a bit more memory.
Still have questions?
Browse all our FAQs or reach out to our support team
