只是想弄清楚這段代碼中“updateCell”引數中的“this”到底指的是什么:
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;
}
我知道“this”單獨可以參考全域變數,但是沒有名為“this”的全域變數,所以我對它的作業原理有點困惑。
uj5u.com熱心網友回復:
作為引數傳遞給的回呼cell.addEventListener稍后將被呼叫,并將其this設定為系結事件處理程式的 DOM 元素。所以在你的代碼中將是cell.
如果您發現使用this混淆,您可以使用以下代替:
問題是回呼是使用事件物件作為引數呼叫的。如果您愿意,您還可以使用該事件物件及其currentTarget屬性來找出所關注的 DOM 元素:
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();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/525233.html
下一篇:R函式創建自定義變數名稱
