whatstheoutput_

#74: An arrow property vs a method

Topic: this · Difficulty: ★★

const obj = {
  name: 'Ann',
  regular() { return this.name; },
  arrow: () => this.name,
};
console.log(obj.regular());
console.log(obj.arrow());

Output

Ann
undefined

Why

A regular method (the shorthand `regular() {}` syntax) gets its this from HOW it's called: obj.regular() calls it as a property of obj, so this is obj, and this.name is 'Ann'. Arrow functions have no this of their own — they capture this lexically from where they were DEFINED, ignoring how they're later called. arrow was defined directly inside the object literal, which is not a function body, so its this is whatever this was in the surrounding script — under node -e that's the global object, which has no name property, so this.name is undefined.

More this puzzles

Play today's puzzle →