0

Here is a class.

class Person {
  constructor() {
    this.age = 25;
  }

  increaseAge(n) {
    this.age += n;
  }
}

Now if I create its instance and destructure increaseAge and call it,

const person = new Person();
const { increaseAge } = person;
increaseAge(2);

I get Uncaught TypeError: this is undefined. Can anyone explain why?

I expected it to work. But it didn't.

nslcoder
  • 11
  • 1
  • `this` is a very peculiar thing in JavaScript. You can look in the [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) for details. – tromgy Nov 20 '22 at 02:49
  • See [How does the "this" keyword work, and when should it be used?](/q/3127429/4642212). `increaseAge(2);` is a call without a `this` context. This comes directly from the [runtime semantics](//tc39.es/ecma262/#sec-function-calls) of this particular syntax. The context of `person` is not bound to the function `increaseAge`. You can explicitly bind it or call it with the correct context: `increaseAge.bind(person)(2)`, `increaseAge.call(person, 2);`. But I guess the lesson is: don’t destructure methods. – Sebastian Simon Nov 20 '22 at 05:28

0 Answers0