0

I have a game written in JavaScript that stores lots of game related data in objects. For example, the map of the world is written in a class like this:

const theMap = new GameMap();

class GameMap() {
    constructor() {
        this.rooms = [];
    }
    addRoom(name) {
        this.rooms.push(name);
    }
}

I want to store the variable theMapin a string so I can write it to a file. I can use JSON.stringify(theMap) to convert it to JSON, but it removes the methods. If I were to convert the JSON back to an object, I couldn't use addRoom on it anymore. Is there a way to preserve those methods?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Julian Lachniet
  • 223
  • 4
  • 25
  • 2
    Does this answer your question? [Using JSON.stringify on custom class](https://stackoverflow.com/questions/13589880/using-json-stringify-on-custom-class) – S.Visser Jan 19 '21 at 17:21
  • Why do you need to store logic in your GameMap? Surely the data is the only thing that changes between instances of the game. – D M Jan 19 '21 at 17:21
  • Does not make sense to stringinfy the class. Make a save method that outputs data in some format. And on init, you can look for the data and import it back in. – epascarello Jan 19 '21 at 17:21
  • 2
    I think you're looking for serialization – AL_1 Jan 19 '21 at 17:22
  • Actually, [`JSON.stringify()` can be configured to store functions](https://stackoverflow.com/questions/40875630/javascript-save-object-with-methods-as-a-string/40876342#40876342). – Scott Marcus Jan 19 '21 at 17:27

0 Answers0