When calling methods of a class object, the reference to this is lost

In our project, we are using the TypeScript Runtime library for our server. When working with class methods, objects often lose this. which leads to errors and attempts to get property of undefined.

So instead of the method :
public SomeMethod = (playerID: number, card: Card): void => {
this.players[playerID].PlayFromHand(card);
};

you have to write methods that take a reference to the current object

public SomeMethod = (originalClass: OriginalClass, playerID: number, card: Card): void => {
originalClass.players[playerID].PlayFromHand(card);
};

And in the same place the call
originalClass.SomeMethod(1, card) won’t work.
originalClass.SomeMethod(originalClass, 1, card) - will work.

Why does it work this way and how to deal with it?

Hello @balex499,

This is a current limitation of the JS runtime, we’re working on improvements to resolve it but there’s not a release date at this stage.

The object references to the functions is lost because of how the JS runtime interacts with Go code of the server.

For now, the best way to avoid these issues is to treat the state as a plain object with only parameters and have auxiliary functions that manipulate it not being tied to the object itself.

Best.

1 Like

Thanks for the quick response! Have a good day!