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?