Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

Why does this become undefined when you extract a method?

Do you know what will be the output of this code?

JavaScript
class User {
  name = "Ana";
  getName() {
    return this.name;
  }
}

const getName = new User().getName;
console.log(getName());
Show answer and explanation

The answer is TypeError: Cannot read properties of undefined.

this is set by how a function is called, not where it’s defined. getName() is called on its own, so this is undefined (class bodies are always in strict mode).

Fix it with .bind(user) or an arrow function property.

Take the full quiz Next question →

More this questions

  1. Why does an arrow function method return undefined for this?
  2. Can you change this on a bound function with call()?
  3. Why does an arrow function in setTimeout keep this?
  4. What is the difference between call and apply in JavaScript?
  5. What happens when a constructor returns an object?

Related topics