1

Have a problem. I create my game object like this:

var game_status = {
    money          : 350000000,
    reset_status   : function() {
        this.money         = 350000000;
    }
}
function saveGame(){
    localStorage.setItem('game_status', JSON.stringify(game_status));
}
function loadGame(){
    game_status     = JSON.parse(localStorage.getItem('game_status'));
}

After loading game status method "reset_status" doesn't exists anymore.

Probably I should describe object, create instance, save instance, and then loading creating instance anew with parameters from load?

Areso
  • 67
  • 1
  • 2
  • 11

3 Answers3

2

Just assign the stored state to the object:

Object.assign(game_status, JSON.parse(localStorage.getItem('game_status')));

That way you don't have to write a constructor.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

Since anyhow object state & object behavior lies within a simple hash and assuming what's needed here is a quick patch, I would do something like:

var INITIAL_GAME = {
    money          : 350000000
},
game_status; 

function saveGame(){
    // strip behavior
    delete game_status.resetGame;
    localStorage.setItem('game_status', JSON.stringify(game_status));

}
function loadGame(){
    game_status = JSON.parse(localStorage.getItem('game_status'));
    if (!game_status) {
    // init by cloning initial object
        game_status = JSON.parse(JSON.stringify(INITIAL_GAME));
    }
    // set behavior again
    game_status.resetGame = function resetGame() {
       this.money = 350000000;
    }
 }

 loadGame();
itavq
  • 135
  • 9
  • Thank you for your answer. There is a notice, though. JSON.stringify() will drop any methods in object, so there is no need to delete object's methods. – Areso Jul 22 '18 at 18:34
0

for (var attrname in game_statusTemp) { game_status[attrname] = game_statusTemp[attrname]; }

A quick workaround for my case. Found in How to duplicate object properties in another object? and How can I merge properties of two JavaScript objects dynamically?

Areso
  • 67
  • 1
  • 2
  • 11