Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
Variable inside Module keeps on returning undefined

I want to modify variable currentPlayer each turn. I have added PlayerController.switchPlayer() to an event listener as well. But every time currentPlayer fails to get updated and returns undefined. I even tried moving the same variable to global as an undefined and still it will fail to get updated despite the code running through the whole if/else block.

const PlayerController = (() => {
  let playerO = Player("O");
  let playerX = Player("X");
  let currentPlayer;
  let switchPlayer = () => {
    if (!playerO.activePlayer) {
      playerO.activePlayer = true;
      playerX.activePlayer = false;
      currentPlayer = playerO;
    } else if (playerO.activePlayer && !playerX.activePlayer) {
      playerX.activePlayer = true;
      playerO.activePlayer = false;
      currentPlayer = playerX;
    }
  };
  return { playerO, playerX, switchPlayer, currentPlayer };
})();
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The object to be returned is calculated once - at the end of the IIFE. Calling switchPlayer and reassigning the local currentPlayer does not change the returned object with the currentPlayer property, because the object has already been evaluated and returned.

You could make currentPlayer into a getter instead, so that it returns the possibly-reassigned value inside the IIFE:

return {
  playerO,
  playerX,
  switchPlayer,
  get currentPlayer() {
    return currentPlayer;
  }
};

But I'd prefer to not hide the fact that it's a function, so that you call getCurrentPlayer from the outside.

return {
  playerO,
  playerX,
  switchPlayer,
  getCurrentPlayer: () => currentPlayer
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda