call(back)

Predict the Output: `this` in an Arrow Method

What do the two lines print? Explain why.

const shape = {
  radius: 10,
  diameter() {
    return this.radius * 2;
  },
  perimeter: () => 2 * Math.PI * this.radius,
};

console.log(shape.diameter());
console.log(shape.perimeter());

Hints

Hint 1

A regular method gets this from the call site. An arrow function has no this of its own.

Solution

Show the approach

Answer: 20, then NaN

An arrow function takes this from where it is defined, and an object literal is not a scope. In a classic script that outer this is window, so this.radius is undefined and the product is NaN. In an ES module the second line throws a TypeError instead, because top-level this is undefined. Naming that difference is the stronger answer.

Asked at