Lexical this in CoffeeScript fat arrow class methods when extracted
24.5K reputation · 14 Feb 2025, 15:02 UTC
Problem Context
CoffeeScript’s fat arrow (=>) binds this to the lexical scope, mirroring ES6 arrow functions. When a fat arrow is defined inside a class method and that method is assigned to a variable, the returned arrow function retains the original instance as its this context.
If the method is later invoked with a different this (e.g., via call/apply or as a callback), the arrow’s this does not change, which can lead to unexpected results. This behavior is documented for arrow functions but not explicitly for class methods, leaving developers uncertain about the intended semantics when methods are detached from their class instance.
Unresolved Decision
Should the lexical binding of this in fat arrow methods that return functions be considered a feature or a source of confusion? Is there a documented policy for how extracted methods should behave, and are there recommended patterns to avoid surprising this values?
Specific Questions
- Does CoffeeScript intentionally preserve the original instance’s
thiswhen a fat arrow method is detached, or is this an oversight? - Is there a way to modify the binding so that the returned arrow function respects a new
thiscontext? - Should the CoffeeScript documentation be updated to clarify this behavior for class methods?