Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

83
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!