tezvyn:

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

Source: developer.mozilla.orgintermediate

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.

This tests the difference between runtime this binding and lexical scope in TypeScript. A strong answer explains that regular functions receive this from the call site, not the definition, so extracting a class method and passing it to addEventListener loses the instance reference. It then demonstrates two fixes: defining the method as an arrow function property to lexically capture this, or explicitly binding it in the constructor. A red flag is suggesting var self = this or claiming that TypeScript changes JavaScript binding rules.

Read the original → developer.mozilla.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.

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