It has been noted by other commenters that the probable cause is that this
is not behaving as expected within the function.
If you have a class structured like this:
class Foo {
public myValue: number;
constructor() { this.myValue = 0; }
barOne() { console.log(this.myValue); }
barTwo = () => { console.log(this.myValue); }
}
The barOne
and barTwo
methods will demonstrate different behavior when used as callbacks externally from the class.
This situation arises when utilizing a class instance method as a callback for a button, as in your scenario.
Exploring further into the workings of this
in JavaScript and TypeScript (JavaScript behaves similarly to TypeScript if ECMAScript 6 is supported) can provide valuable insights, with numerous informative articles available on the topic.
However, a straightforward solution is to utilize "arrow functions," as demonstrated in the implementation of the barTwo
method above.