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

90
Visualizações
How to reassign global object from inside a function

I don't seem like the variable game outside of createNewGame is updated with the same value as the game inside of createNewGame.

Is there any way I can update the global game inside of the createNewGame function?

export let game = new Game(settings);

export const createNewGame = (updatedSettings) => {
  game = new Game(Object.assign(settings, updatedSettings), true)
  game.test = 'test'
  //reset state
  runGame(game);
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Inside this module, the value of game will be updated when you call createNewGame(). That's pretty easy to test and verify.

But, I see you are exporting game. When someone uses that export, they are getting the current value of the game variable and they are putting that current value into their own variable. When you then assign a new value to this local game variable in this module when createNewGame() is called, the module that used the export will still have the original value of that game variable in their variable. Their own variable that they assigned the exported value into will not be updated.

The way around that would be to export an object that does not change and make the game be a property on that object.

export let gameObj = { game: new Game(settings) };

export const createNewGame = (updatedSettings) => {
  gameObj.game = new Game(Object.assign(settings, updatedSettings), true)
  gameObj.game.test = 'test'
  //reset state
  runGame(gameObj.game);
}

This works because you aren't reassigning gameObj, just a property on that object. So, both your local gameObj and anyone who used the exported gameObj will both have references to the same gameObj object. And, when you change the gameObj.game property, then both the local reference and the exported reference will see the new value of that property.

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