在我的函数中,"this"单独指的是什么?



我只是想把我的头完全围绕着什么"这个";单独在";updateCell";此代码中的参数:

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;
}

我知道";这个";单独可以引用全局变量,但没有称为"的全局变量;这个";所以我有点困惑这是怎么回事。

作为参数传递给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();
}

最新更新