Arrow Functions Take this from the Surrounding Scope, So They Make Poor Object Methods

In progress

Arrow functions ((a, b) => a + b) are a shorter way to write function expressions, but they are not just syntax: they have no this of their own and use the this of the code around them. That makes them ideal for callbacks inside methods, and wrong as methods themselves, where this should be the object.

Syntax

const add = (a, b) => {
  return a + b;
};
const addShort = (a, b) => a + b;     // single expression: implicit return
const square = x => x * x;            // one parameter: parentheses optional
const makeUser = name => ({ name });  // returning an object literal needs ( )

The this Trap

const speaker = {
  name: "John",
  sayHi: () => console.log(`Hi, I'm ${this.name}!`),   // this is not speaker
  sayHello() { console.log(`Hello, I'm ${this.name}!`); },
};

speaker.sayHi();      // Hi, I'm undefined! (in a CommonJS module)
speaker.sayHello();   // Hello, I'm John!

sayHi was created where this was the module or global scope, and calling it through speaker doesn't change that. A regular function's this is decided at call time, by what is left of the dot; an arrow function's this is fixed when it is created, like any other variable it closes over. In a Node CommonJS module that outer this is module.exports, so this.name is quietly undefined; at the top level of an ES module this is itself undefined and the call throws a TypeError instead.

Where Lexical this Helps

Inside a method, a callback that needs the object's this is exactly the case arrows were made for:

class Timer {
  constructor() { this.seconds = 0; }
  start() {
    setInterval(() => { this.seconds += 1; }, 1000);   // this is the Timer
  }
}

With a regular function callback, this would be lost and the counter would never increase, which used to require const self = this or .bind(this).

References

Review cards

Flashcard Why are arrow functions wrong as object methods?

They have no this of their own: they use the this of the code around them, which isn't the object. Use method shorthand (sayHello() {}) instead.

Flashcard When is `this` decided for a regular function, and for an arrow function?

Regular: at call time, by what is left of the dot. Arrow: when it's created, like any other variable it closes over.

Quiz `sayHi: () => console.log(this.name)` sits in an object literal at the top level of an ES module. What does `speaker.sayHi()` do?
  • Throws a TypeError: this is undefined
  • Logs the object's name
  • Logs undefined
  • Logs the global object's name

At the top level of an ES module this is undefined, so reading .name throws. In a CommonJS module it's module.exports, and the call quietly logs undefined.

Flashcard Where is an arrow function's lexical `this` exactly what you want?

For a callback inside a method, such as setInterval(() => { this.seconds += 1; }, 1000): this stays the object. A regular function would lose it, which used to need self = this or .bind(this).