0

I have this code:

class Executor {
  name: string;
  startDate: Date;
  endDate: Date;
  steps: { (): Promise<void> }[];

  constructor(startDate: Date, endDate: Date) {
    this.name = 'chartNoteFaxing';
    console.log(`Setting startDate ${startDate} and endDate: ${endDate}`);
    this.startDate = startDate;
    this.endDate = endDate;
    console.log(`this.startDate ${this.startDate} this.endDate: ${this.endDate}`);
    this.steps = [
      this.sayHi,
    ];
  }

  async sayHi() {
    console.log('GOT HERE???')
    console.log(`${this}`);
    console.log(`Hi! Got to here with ${this.name}`);
  }

  async execute() {
    for (const step of this.steps) {
      console.log('About to run step');
      console.log(`${this}`);
      await step();
    }
  }  
}

and for some reason here is the output:

[LOG]: "Setting startDate Mon Nov 28 2022 00:00:00 GMT-0500 (Eastern Standard Time) and endDate: Mon Nov 28 2022 19:00:00 GMT-0500 (Eastern Standard Time)" 
[LOG]: "this.startDate Mon Nov 28 2022 00:00:00 GMT-0500 (Eastern Standard Time) this.endDate: Mon Nov 28 2022 19:00:00 GMT-0500 (Eastern Standard Time)" 
[LOG]: "About to run step" 
[LOG]: "[object Object]" 
[LOG]: "GOT HERE???" 
[LOG]: "undefined" 

Obviously, the issue in the sayHi method is that this is undefined. It's even more strange, because it's defined right before the await step(). I'm not sure why. The class has been instantiated so why would referencing this in typescript break it?

jlarks32
  • 931
  • 8
  • 20
  • Yeah that seems to be a good link. So you're saying I could do something like `this.sayHi.bind(this)` in the constructor? That seems.... oddd – jlarks32 Dec 02 '22 at 17:12
  • 1
    `this.steps = [this.sayHi.bind(this)];` or `this.steps = [() => this.sayHi()];` would work. The problem is that putting `this.sayHi` into an array apparently loses connection to knowing what `this` is. This is more common seen passing a class method into other code, like `setTimeout(this.sayHi, 20)`. – crashmstr Dec 02 '22 at 17:14

0 Answers0