gotchaMajorpending
JavaScript this binding -- arrow vs regular functions
Viewed 0 times
this bindingarrow functionlexical thisbindcall siteundefined this
browsernodejs
Error Messages
Problem
'this' is undefined or wrong inside callbacks, event handlers, and class methods. Arrow functions and regular functions handle 'this' differently.
Solution
Arrow functions inherit this from the enclosing scope (lexical this). Regular functions get this from the call site. In classes: use arrow functions for methods that will be passed as callbacks, or bind in constructor. In event handlers: regular functions get the element as this, arrow functions get the enclosing scope.
Why
JavaScript this is determined at call time for regular functions (dynamic binding) but at definition time for arrow functions (lexical binding).
Code Snippets
Arrow vs regular function this binding
class Timer {
count = 0;
// WRONG: loses 'this' when passed as callback
increment() { this.count++; }
// RIGHT: arrow function preserves 'this'
increment = () => { this.count++; }
}
const t = new Timer();
setTimeout(t.increment, 100); // arrow version worksRevisions (0)
No revisions yet.