Skip to content
tezvyn:

Why does this lose context in class callbacks and two TypeScript fixes?

Source: developer.mozilla.orgMediumHow cards are made

Why does this lose context in class callbacks and two TypeScript fixes?

This tests runtime this binding. Explain that regular functions get this from the call site, so passing a method strips its object context. Fix with an arrow property or constructor bind. Red flag: var self = this or claiming TypeScript changes binding.

What's really being asked

This question tests whether you understand that the value of this in JavaScript and TypeScript is determined by how a function is invoked, not how it is written. It specifically checks if you know that regular functions use runtime binding, which means detaching a method from its object and passing it as a callback causes this to become undefined in strict mode or the global object otherwise. It also checks your fluency with TypeScript class syntax and modern fixes that preserve context without resorting to legacy patterns.

The full answer

First, explain the mechanism: when you write element.addEventListener('click', myInstance.handleClick), you are passing a reference to the function only, severing its connection to myInstance. At call time, the browser invokes it as a standalone function, so this no longer points to the class instance. Second, present two distinct fixes. Fix one is an arrow function property: handleClick = () => { ... } defined as a class field. Arrow functions inherit this from the surrounding scope at definition time, so the instance is permanently captured. Fix two is explicit binding in the constructor: this.handleClick = this.handleClick.bind(this); this creates a new bound function that ignores future call-site context. Both are valid, but the arrow property is more concise.

The mistakes people make

A major red flag is suggesting var self = this as a TypeScript solution; that is an obsolete ES5 workaround and signals weak modern language knowledge. Another red flag is claiming that TypeScript changes how this works; TypeScript compiles to JavaScript and leaves binding semantics entirely intact. Also avoid saying that bind, call, or apply can fix an arrow function, because arrow functions do not have their own this binding and cannot be rebound.

What usually comes next

An interviewer might ask which fix you prefer and why. The arrow property is cleaner but creates a new function per instance, slightly increasing memory use compared to a prototype method. They might also ask how this behaves in subclassing scenarios, or how to type the event parameter correctly in TypeScript when using addEventListener with a bound method.

A concrete example

Imagine a Button class with a method onClick that reads this.label. If you register it with buttonElement.addEventListener('click', button.onClick), clicking throws an error because this is undefined. To fix it, define onClick as an arrow function property: onClick = (event: MouseEvent) => { console.log(this.label); }. Alternatively, in the constructor write this.onClick = this.onClick.bind(this); and keep the method as a regular prototype method. Both ensure this refers to the Button instance when the DOM event fires.

Interview question

Which of the following correctly fixes lost this context in a class callback?

  • a.TypeScript strict mode enables automatic this binding for class methods
  • b.Defining the method as an arrow function property or binding it in the constructorCorrect
  • c.Arrow functions can be rebound later with bind(this) if context is lost
  • d.Using var self = this is the preferred TypeScript approach
Why?

The card identifies an arrow function class field and explicit constructor binding as the two modern fixes. Option C is tempting but wrong because arrow functions do not have their own this binding and cannot be rebound.

Just read this? Test yourself on what you have been reading.

Read the original → developer.mozilla.org

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on typescript — each one lists the topics its interview covers.

See open roles