Just trying to wrap my head around exactly what "this" alone in the "updateCell" parameter refers to in this code:
function initializeGame() {
cells.forEach(cell => cell.addEventListener("click", cellClicked))
restartBtn.addEventListener("click", restartGame);
statusText.textContent = `${currentPlayer}'s turn`;
running = true;
}
function cellClicked(){
console.log('test');
const cellIndex = this.getAttribute("cellIndex");
if(options[cellIndex] != "" || !running) {
return;
}
updateCell(this, cellIndex);
checkWinner();
}
function updateCell(cell, index) {
options[index] = currentPlayer;
cell.textContent = currentPlayer;
}
I know "this" alone can reference a global variable, but there is no global variable called "this" so I'm a little confused on how this works.
CodePudding user response:
The callback that is passed as argument to cell.addEventListener
will later be called with this
set to the DOM element on which the event handler is bound. So in your code that will be cell
.
If you find the use of this
confusing, you can use the following instead:
The thing is that the callback is called with an event object as argument. If you prefer, you can also use that event object and its currentTarget property to find out which DOM element is concerned:
function cellClicked(evt){
const cell = evt.currentTarget;
// At this point, `cell===this` is true
const cellIndex = cell.getAttribute("cellIndex");
if(options[cellIndex] != "" || !running) {
return;
}
updateCell(cell, cellIndex);
checkWinner();
}