3

I have the following typescript class

export default class BaselineCtrl {
  constructor() {}

  async foo() {
    this.bar();
  }

  async bar() {}
}

When I call the method via

baselineCtrl = new BaselineCtrl();
this.baselineCtrl.foo();

Im getting the error

TypeError: Cannot read properties of undefined (reading 'bar')

What am I doing wrong?

guygrinberger
  • 327
  • 2
  • 14

2 Answers2

3

Check usage of arrow function. https://www.typescriptlang.org/docs/handbook/functions.html#this-and-arrow-functions

In JavaScript, this is a variable that’s set when a function is called.

Change your function like this:

async foo = () => {
    this.bar();
}

PS: why async here ?

Gilsdav
  • 1,147
  • 7
  • 10
  • It worked! Thanks for the answer and the explanation. The async is there because I forgot to remove it for the example. – guygrinberger Oct 21 '21 at 07:29
3

baselineCtrl and this.baselineCtrl refer to two different things, the first one is a local variable (presumably) and the second one is a property on the current object. I'm not sure which one of them you want, it depends on what you're trying to do, but you definitely want the same one in both places.

Guillaume Brunerie
  • 4,676
  • 3
  • 24
  • 32