I am adding an event listener to a button inside of an object method. I am attempting to add a call to another method function but when I use this.reset() the 'this' points to the listener//button rather than the object itself.
This code has been refactored into an object and was working fine before. In that case I didn't need to use 'this'.
const colorGame = {
reset: function() {...},
init: function() {
for (let i = 0; i < modeSwitches.length; i++) {
modeSwitches[i].addEventListener("click", function() {
modeSwitches[0].classList.remove('selected');
modeSwitches[1].classList.remove('selected');
// These two lines are why I can't use anonymous functions
this.classList.add('selected');
this.textContent === 'Easy' ? numSquares = 3 : numSquares = 6;
this.reset();
});
}
...
resetButton.addEventListener('click', function() {
this.reset(); // This call also fails with the same error
});
Error in Chrome browser console : colorGame.js:78 Uncaught TypeError: this.reset is not a function
My intent is to use colorGame.reset() and have that called when the buttons are clicked.