I have an object constructor function that I use to create an object for a Conway's Game of Life simulator. A table element is used to render the game and the cells.
A user can click on a cell to toggle it being alive/dead. For this reason, every cell has an event listener,
cell.addEventListener( 'click', myObjConstructor.toggleState )
The way handlers work is that when the listener calls the handler function, "this" refers to the element the listener is placed in (rather than the object's this) which is why this wouldn't work:
cell.addEventListener( 'click', this.toggleState )
Because this would reference the element (the cell) which wouldn't have a "toggleState" method thus results in an error.
I think this is pretty standard knowledge regarding handlers. My question is, what is the most "professional" way of dealing with this when you want to reference the object's this?
The way I am dealing with it is I declare this dummy variable at the beginning of my object:
myBackupThis = this;
However, this feels "cheap". I am assuming the pros must handle it in a different way.
I tried an arrow function but it doesn't solve the problem that "this" is not pointing to the object.