在给定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
相关产品推荐
相关产品推荐

