Hone

Lessons · JavaScript · arrow functions and this

Arrows keep the this they were born in

An arrow function has no this of its own; it uses the this of the code around it. A regular function gets its own this, set by how it is called.

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

A callback inside a method that needs the object: with a regular function, this is lost; with an arrow, it is the object. This replaced the old const self = this dance.

How to think about it

Inside a method, use arrows for callbacks that need the object. Use a regular function or method syntax for the method itself, because an arrow at the object level has no object this.

Worked example

const timer = { label: "t", start() { setTimeout(() => console.log(this.label), 0); } };
The arrow keeps the this from start(): the timer object.
const timer2 = { label: "t2", start() { setTimeout(function () { console.log(this && this.label); }, 0); } };
A regular function gets its own this, which is not the timer.
timer.start(); timer2.start();
t, then undefined.

Your turn

A click handler that keeps the component's this.

button.addEventListener("click",  => this.save());

The trap

{ name: 'x', hi: () => this.name } does not work: an arrow written directly on an object has no object this. Use a method for that, an arrow inside it.

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