我有一个模块模式,其中一个变量将 currentPlayer 设置为 1。我使用函数表达式来切换该变量
const game = (() => {
let currentPlayer = 1;
const toggleCurrentPlayer = () => {
if (currentPlayer == 1){
currentPlayer = 2 ;
}
else {
currentPlayer = 1;
}
};
return {currentPlayer, toggleCurrentPlayer};
})();
如果我运行game.currentPlayer
它会记录 1,然后我运行game.toggleCurrentPlayer()
,并且它没有currentPlayer
按预期更改,它仍然返回 1。
但是,toggleCurrentPlayer()
使用 , 更改函数this
似乎能够成功更改变量
function toggleCurrentPlayer(){
if (this.currentPlayer == 1){
this.currentPlayer=2;
}
else if (this.currentPlayer == 2){
this.currentPlayer=1;
}
};
我知道函数声明和函数表达式对关键字有不同的含义this
,但是为什么toggleCurrentPlayer()
只有this
关键字才能正常工作而不能自行设置变量呢?