You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在给定JavaScript代码中,函数参数里的this关键字指向什么?

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

疑问解析

你困惑的updateCell(this, cellIndex)里的this,并不是全局变量,它的指向由函数的调用方式决定:

  • cellClicked作为点击事件的回调函数,被绑定到cells数组中的每个DOM单元格元素上(比如页面上的<td>或<div>这类代表游戏格子的元素)。
  • 当用户点击某个单元格时,浏览器触发click事件并调用cellClicked函数,此时this默认指向触发该点击事件的那个DOM单元格元素——和你在const cellIndex = this.getAttribute("cellIndex")里用到的this是同一个对象。

简单来说,你点击哪个游戏格子,this就指向哪个格子的DOM节点,把它传给updateCell后,函数就能修改这个格子的文本内容,标记当前玩家的操作。

内容的提问来源于stack exchange,提问作者Brenden Baio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 03:45:55