localStorage won't save objects containing arrow functions

Viewed 446

I'm making a small web-based RPG using Javascript, unfortunately once it came to implementing my saving and loading feature, a critical part of my code just failed completely.

As of now I'm saving all the player data in my player object:

var player = {
    stats: {
        level: 1,
        healthBase: 50,
        health: 50,
        strength: null,
        strengthBase: 7,
        strengthMods: {
        },
    },
};

Using these two functions:

function save() {
    localStorage.setItem("playerData", JSON.stringify(player));
}

function load() {
    player = JSON.parse(localStorage.getItem('playerData'));
}

This works perfectly for everything, except for one small part. In certain situations I need to add modifiers to my stats to change them, I do that like so

player.stats.strengthMods.mods = () => ( 5 );

However, if I save and then load my game, after calling

player.stats.strengthMods.mods

The console will only show me an empty object. I can't understand why my browser refuses to load the arrow function, everything else is loading perfectly apart from that.

Any idea why?

1 Answers

JSON doesn't have any way to store function definitions; it's a data serialization format, not an arbitrary object serialization format. Since you must JSONify to put the value in localStorage, you can't preserve functions. localStorage isn't the direct problem here; even if you never used it, the function wouldn't survive the round trip to JSON and back.

Related