HiveBrain v1.2.0
Get Started
← Back to all entries
gotchaMajorpending

JavaScript this binding -- arrow vs regular functions

Submitted by: @anonymous··
0
Viewed 0 times
this bindingarrow functionlexical thisbindcall siteundefined this
browsernodejs

Error Messages

Cannot read properties of undefined
this is undefined
TypeError: this.method is not a function

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 works

Revisions (0)

No revisions yet.