在JavaScript类方法中,无法使用';这';在addEventListener()内部,甚至使用箭头函数。如何解决这个问题

在JavaScript类方法中,无法使用';这';在addEventListener()内部,甚至使用箭头函数。如何解决这个问题,javascript,class,methods,this,arrow-functions,Javascript,Class,Methods,This,Arrow Functions,我为井字游戏写了一节课。代码运行良好,但我必须在类定义中使用对象名来调用一些方法,而不是“this”关键字。当方法作为回调传递给addEventListener()时,就会出现问题。 我试图通过使用箭头函数定义方法来解决这个问题。但JS显示错误“无法读取未定义属性”错误。 我将如何克服这种情况 下面是类的实现。你可以看到我用game.turnClick代替了这个.turnClick class TicTacToe{ constructor(aiPlayer,humanPlayer

我为井字游戏写了一节课。代码运行良好,但我必须在类定义中使用对象名来调用一些方法,而不是“this”关键字。当方法作为回调传递给addEventListener()时,就会出现问题。 我试图通过使用箭头函数定义方法来解决这个问题。但JS显示错误“无法读取未定义属性”错误。 我将如何克服这种情况

下面是类的实现。你可以看到我用game.turnClick代替了这个.turnClick

    class TicTacToe{
    constructor(aiPlayer,humanPlayer){

        this.aiPlayer=aiPlayer;
        this.humanPlayer=humanPlayer;
        this.winCombos=[
            [0,1,2],
            [3,4,5],
            [6,7,8],
            [0,3,6],
            [1,4,7],
            [2,5,8],
            [0,4,8],
            [2,4,6]
        ];
        this.originalBoard=Array.from(Array(9).keys());
        this.gameWon=null;
        this.cells=document.querySelectorAll('.cell');


    }
    startGame(){
        //const cells=document.querySelectorAll('.cell');
        this.cells.forEach(function(cell){
            cell.innerHTML="";
            cell.addEventListener('click',game.turnClick);
        })
    }
    turnClick(e){
        game.turn(e.target.id,game.humanPlayer);
        if(!game.isTie()&&!game.gameWon){
            window.setTimeout(function(){
                game.turn(game.bestSquare(),game.aiPlayer);
                game.isTie();
            },1500);

        }
    }
    turn(squareId,player){
        this.originalBoard[squareId]=player;
        const square=document.getElementById(squareId);
        square.innerHTML=player;
        document.querySelector('#click').play();
        square.removeEventListener('click',game.turnClick);
        this.gameWon=this.checkWin(this.originalBoard,player);
        if(this.gameWon){
            this.gameOver();
        }



    }
    checkWin(board,player){
        let playedSquares=[];
        board.forEach(function(el,i){
            if(el===player){
                playedSquares.push(i);
            }
        })
        console.log(playedSquares);
        for(let [index,win] of this.winCombos.entries()){
            if(win.every((el)=>{return playedSquares.includes(el)})){
            return {index,player};
            break;
            }
        }
        return null;
    }
    gameOver(){
        for(let index of this.winCombos[this.gameWon.index] ){
            const square=document.getElementById(index);
            square.style.backgroundColor= this.gameWon.player===this.humanPlayer?"blue":"red";
        }
        //const cells=document.querySelectorAll('button.cell');
        this.cells.forEach(function(cell){
            cell.removeEventListener('click',game.turnClick);
        });
        this.declareWin(this.gameWon.player===this.humanPlayer?'You Won !!! Hurray...':'You loose,AI beat you...');
    }
    emptySquares(){
        return this.originalBoard.filter((el)=>typeof el==='number');
    }
    bestSquare(){
        //return this.emptySquares()[0];
        return this.minimax(this.originalBoard, this.aiPlayer).index;
    }
    isTie(){
        if(this.emptySquares().length===0&& !this.gameWon){
            this.cells.forEach(function(cell){
                cell.style.backgroundColor='green';
                cell.removeEventListener('click',game.turnClick);
            });
            this.declareWin(' You managed tie the game. congrats !!!');
            return true;
        }
        else{
            return false;
        }
    }
    declareWin(msg){
        if(msg.includes('won')||msg.includes('tie')){
            document.querySelector('#winOrTie').play();
        }
        else{
            document.querySelector('#lost').play();
        }
        document.querySelector('.endgame .message').innerText=msg;
        document.querySelector('.endgame').classList.add('show');
    }
    minimax(newBoard,player){
        let availSpots = this.emptySquares();

        if (this.checkWin(newBoard, this.humanPlayer)) {
            return {score: -10};
        } else if (this.checkWin(newBoard, this.aiPlayer)) {
            return {score: 10};
        } else if (availSpots.length === 0) {
            return {score: 0};
        }
        let moves = [];
        for (let i = 0; i < availSpots.length; i++) {
            let move = {};
            move.index = newBoard[availSpots[i]];
            newBoard[availSpots[i]] = player;

            if (player === this.aiPlayer) {
                let result = this.minimax(newBoard, this.humanPlayer);
                move.score = result.score;
            } else {
                let result = this.minimax(newBoard, this.aiPlayer);
                move.score = result.score;
            }

            newBoard[availSpots[i]] = move.index;

            moves.push(move);
        }

        let bestMove;
        if(player === this.aiPlayer) {
            let bestScore = -10000;
            for(let i = 0; i < moves.length; i++) {
                if (moves[i].score > bestScore) {
                    bestScore = moves[i].score;
                    bestMove = i;
                }
            }
        } else {
            let bestScore = 10000;
            for(let i = 0; i < moves.length; i++) {
                if (moves[i].score < bestScore) {
                    bestScore = moves[i].score;
                    bestMove = i;
                }
            }
        }

        return moves[bestMove];

    }
}
classtictactoe{
构造函数(aiPlayer、humanPlayer){
this.aiPlayer=aiPlayer;
this.humanPlayer=humanPlayer;
这是winCombos=[
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[2,4,6]
];
this.originalBoard=Array.from(Array(9.keys());
this.gameWon=null;
this.cells=document.querySelectorAll('.cell');
}
startGame(){
//const cells=document.queryselectoral('.cell');
this.cells.forEach(函数(单元格){
cell.innerHTML=“”;
cell.addEventListener('click',game.turnClick);
})
}
点击按钮(e){
游戏。回合(例如,target.id,game.humanPlayer);
如果(!game.isTie()&&!game.gameWon){
setTimeout(函数(){
game.turn(game.bestSquare(),game.aiPlayer);
game.isTie();
},1500);
}
}
转身(方线,球员){
这个.originalBoard[squared]=玩家;
const square=document.getElementById(squareId);
square.innerHTML=player;
document.querySelector('#click').play();
square.removeEventListener('click',game.turnClick);
this.gameWon=this.checkWin(this.originalBoard,player);
如果(this.gameWon){
这是gameOver();
}
}
checkWin(棋盘、玩家){
让playedSquares=[];
董事会主席(职能(el,i){
如果(el==玩家){
游戏方块。推(i);
}
})
控制台.log(playedSquares);
对于(让[index,win]this.winCombos.entries()){
if(win.every((el)=>{return playedSquares.includes(el)})){
返回{index,player};
打破
}
}
返回null;
}
gameOver(){
for(让我们索引this.winCombos[this.gameWon.index]){
const square=document.getElementById(索引);
square.style.backgroundColor=this.gameWon.player==this.humanPlayer?“蓝色”:“红色”;
}
//const cells=document.querySelectorAll('button.cell');
this.cells.forEach(函数(单元格){
cell.removeEventListener('click',game.turnClick);
});
这个.declareWin(这个.gameWon.player==这个.humanPlayer?“你赢了!!!万岁…”:“你输了,AI赢了你…”);
}
空方块(){
返回这个.originalBoard.filter((el)=>typeof el==='number');
}
bestSquare(){
//返回此.emptySquares()[0];
返回this.minimax(this.originalBoard,this.aiPlayer).index;
}
isTie(){
if(this.emptySquares().length==0&&!this.gameWon){
this.cells.forEach(函数(单元格){
cell.style.backgroundColor='green';
cell.removeEventListener('click',game.turnClick);
});
这个。declareWin(‘你打平了比赛。恭喜!!!’);
返回true;
}
否则{
返回false;
}
}
declareWin(味精){
if(msg.includes('won')| | msg.includes('tie')){
document.querySelector('#winOrTie').play();
}
否则{
document.querySelector('\35; lost').play();
}
document.querySelector('.endgame.message')。innerText=msg;
document.querySelector('.endgame').classList.add('show');
}
极小极大值(新手,玩家){
设availSpots=this.emptySquares();
if(这个.checkWin(newBoard,这个.humanPlayer)){
返回{分数:-10};
}否则如果(这个.checkWin(新板,这个.aiPlayer)){
返回{分数:10};
}else if(availSpots.length==0){
返回{score:0};
}
让我们移动=[];
for(设i=0;i最佳分数){
最佳得分=移动[i]。得分;
bestMove=i;
}
}
}否则{
让bestScore=10000;
for(设i=0;i
下面是包含完整代码的gitHub存储库


您可能需要将回调方法的上下文绑定到实例。

是否
game
是全局变量?为什么要在一个特定实例上调用方法而不是使用
this
?“this”不起作用。这就是为什么我必须创建一个类的全局变量
cell.addEventListener('click',game.turnClick.bind(game));