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?

5
  • 2
    Does this answer your question? Using JSON.stringify on custom class Commented Jan 19, 2021 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. Commented Jan 19, 2021 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. Commented Jan 19, 2021 at 17:21
  • 2
    I think you're looking for serialization Commented Jan 19, 2021 at 17:22
  • Actually, JSON.stringify() can be configured to store functions. Commented Jan 19, 2021 at 17:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.