The One-Line Refactor That Made this Become undefined in Production
Unlike languages where this is lexically bound to a class instance at definition time, JavaScript decides what this refers to at the moment a function is called, not where it was written. That single distinction has caused more runtime errors than any other keyword in the language. The refactor looked completely safe. A method called updateUser lived on a userStore object, and a component needed…
In JavaScript, the value of `this` is determined dynamically at the moment a function is called, unlike many other languages like Java, C++, or Python where `this` is bound to the instance at the point a method is defined. This difference in binding models has caused more runtime errors than any other keyword in JavaScript. A refactor that extracted a method reference to make the code more concise led to a production crash.
When the button was clicked, `this` inside the `updateUser` function evaluated to `undefined` because the method had been detached from its original object. This issue occurs frequently when a method is passed somewhere its author didn't anticipate, resulting in unpredictable execution context. Arrow functions are an exception as they capture `this` lexically from the surrounding scope, avoiding the extraction bug.
The problem arises when a method is extracted and invoked without explicitly binding its `this`, often in event handlers or array methods.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.