简体   繁体   English

JS全局变量不会在函数范围之外改变

[英]JS global variable not changing outside of function scope

I'm making a tic-tac-toe game in JS and I'm trying to implement a function inside a ' Game Controller ' module that will handle the player's turn.我正在用 JS 制作井字游戏,我正在尝试在“游戏控制器”模块中实现一个功能,该模块将处理玩家的回合。 The issue I'm running into is that a global property 'currentPlayer' is not getting its value changed outside of the scope of the function that modifies it.我遇到的问题是全局属性“currentPlayer”没有在修改它的函数范围之外更改其值。

I've tried debugging using Dev tools and I can see the value changing but only inside the 'switchPlayerTurn ' function.我尝试使用 Dev 工具进行调试,我可以看到值发生变化,但仅在“switchPlayerTurn ”函数内部。 Any suggestions here?这里有什么建议吗?

const GameController = (() => {
    const activePlayers = [];
    let currentPlayer = ''; 
    
   const _switchPlayerTurn = () => {
        if(currentPlayer === '') {
            currentPlayer = activePlayers[0];
        } else if(currentPlayer === activePlayers[0]){
            currentPlayer = activePlayers[1];
        } else if(currentPlayer === activePlayers[1]){
            currentPlayer = activePlayers[0];
        }
    }

    const init = () => {
        return createPlayers()
        .then(_switchPlayerTurn());
    }

    return {
        init,
        activePlayers,
        currentPlayer,
    }

})();

Returning an object with currentPlayer only results in the object containing the value of currentPlayer at the moment of the return of the object.返回与对象currentPlayer只导致含有的值的对象currentPlayer在对象的返回的时刻。 You need a function instead, so that you can retrieve the current value of the identifier inside on demand.您需要一个函数,以便您可以按需检索内部标识符的当前值。

return {
    init,
    activePlayers,
    getCurrentPlayer: () => currentPlayer,
}

and then, wherever you're using it externally, use .getCurrentPlayer() instead of .currentPlayer然后,无论您在何处使用它,请使用.getCurrentPlayer()而不是.currentPlayer

This isn't as elegant as @certainPerformance's answer, but for the sake of completeness... you could always define it outside your function scope so it is accessible globally all the time这不像@certainPerformance 的回答那么优雅,但为了完整起见......你总是可以在你的函数范围之外定义它,这样它就可以一直在全球范围内访问

let currentPlayer = ''; 
const GameController = (() => {
    const activePlayers = []; 
    // ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM