I have a problem with a scope of keyword 'this'.
The code for instance is:
class Burger {
sleep() {
// To sleep
}
pourSauce(sauce: string) {
// To pour sauce
this.sleep();
}
}
class Hesburger extends Burger {
constructor() {
super();
}
private bun: string = 'bunny';
foo(): void {
this.tmp(this.fat);
}
private fat(): void {
super.pourSauce(this.bun);
}
private tmp(callBack: () => void): void {
callBack();
}
}
Somewhere I call:
Hesburger.foo();
I receive the error:
"bun" is undefined
I have found the post, describing the solution for transmitting a function. But no clue about a class's property.
Can someone advise to transit 'bun' variable's value 'bunny' to function fat(), so it would be transmitted further to function pourSauce()?
Thank you!
The problem is with the following line
this.tmp(this.fat);
where you are passing the fat function as callback to the tmp function. But eventhough you are passing this.fat it is always just a function, that is not bound to a specific context (ie it does not have a defined this anymore). You can work around this issue by explicitely binding the function to a specific context
this.tmp(this.fat.bind(this))