Hone

Lessons · JavaScript · this in methods

this is the object before the dot

Inside a method, this is whatever the method was called on. Detach the method from its object and this is gone.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Event handlers, timers and callbacks all take a function and call it later, without the dot. That is when this.count silently becomes undefined.count and throws, usually far from the line that caused it.

How to think about it

Ask: when this runs, what is before the dot? If nothing will be, bind the method (obj.method.bind(obj)) or wrap it in an arrow (() => obj.method()), which keeps the dot.

Worked example

class Counter {
  constructor() { this.count = 0; }
  tick() { this.count += 1; return this.count; }
this: the object before the dot.
}
const c = new Counter();
c.tick(); c.tick();
this is c both times.
console.log(c.count);
2
const loose = c.tick;
The method, detached from c.
let msg = 'ok';
try { loose(); } catch (e) { msg = 'lost this'; }
No dot, no this: this.count throws.
console.log(msg);
lost this
const bound = c.tick.bind(c);
bind pins this to c for good.
console.log(bound());
3

Your turn

Hand the method to a timer without losing this.

setTimeout( => c.tick(), 1000);

The trap

Passing obj.method as a callback and reading this inside it. The callback is called bare, this is undefined, and the error names a line that looks innocent.

Practise this in methods on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.