Persisting object's methods into localStorage


I am trying to persist an object which has properties and methods into localstorage.

The persistence of the properties works like a charm, but when reading from persistence, all the object’s methods are gone.
This is what i am using:

// Store to persistence
window.localStorage.setItem("key", JSON.stringify(myObject));

// Read from persistence
var myObject = window.localStorage.getItem("key");

Does anyone know what can be done in order to not lose the methods?
Note that I am using JSON.stringify because the object has inner sub-objects as properties.

Thanks in advance

.stringify() doesn’t process functions, only valid JSON types. You could cast it to a string, then store it like that… but I feel like there are probably better ways to accomplish whatever you’re trying to do. I can’t think of a good use case for wanting to store functions inside localStorage. You should rely on browser caching.

As @mawburn said… the local storage is for storing data, not code. You’d have to use eval() or the Function() constructor then, which should generally be avoided as it is slow and a potential security issue.

What you might do though is to just store those objects’ state, create them anew when you need them, and then merge in the stored state using Object.assign() (or pass it to the constructor or factory function, whichever way you choose to create those objects). Like e.g.

// Create an object with methods (probably using a factory
// function or from a class in a real application)
const counter = {
  count: 0,
  increment () {

// Check if there's some state stored in the local
// storage, and if so, assign it to the counter intance
const counterState = localStorage.counterState

if (counterState) {
  Object.assign(counter, JSON.parse(counterState))

// Then somewhere else, do something that modifies state, 
// and persist it to the local storage
localStorage.counterState = JSON.stringify(counter)

Thank you all for the clarifications.
This made is clear that I should only be persisting data and not functions.
I refactored my code and separated the functions form the data. Now everything works like a charm.


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.