Search code examples
javascriptjsonobjectlocal-storage

Retrieve private methods of objects from localStorage


I have defined a factory function to generate objects of a certain "class":

const myObject = function(param) {

  const attribute = param;

  const _privateMethod = function {};

  const publicMethod = function {};

  return {attribute, publicMethod,};

};

const instance = myObject(arg)

And I'm saving this object to localStorage:

const jsonString = JSON.stringify(instance);

window.localStorage.setItem("object", jsonString);

When I recover the objects the methods aren't there of course, so I reassociate the methods to the objects like this:


const rJsonString = window.localStorage.getItem("object");

const rInstance = JSON.parse(rJsonString);

const {publicMethod,} = myObject(rInstance.attribute);

Object.assign(rInstance, {publicMethod,});

Is there a way to reassociate the private methods?


Solution

  • The way that I would do this would be to either:

    1. Create a class for these objects, and add a method to instantiate from a plain js object (this is what you'll get back from JSON.parse)
    class MyObject {
      constructor(plainMyObject) {
        // or whatever
        for (const [key, value] of Object.entries(plainMyObject)) {
          this[key] = value;
        }
      }
    
      publicMethod() {
        this._privateMethod();
        // or
        this.#privateMethod();
      }
    
      _privateMethod() {
        // . . .
      }
    
      // or using real private methods
      #privateMethod() {
      // ...
      }
    }
    
    const obj = new MyObject(JSON.parse(localStorageStringValue));
    obj.publicMethod();
    
    1. Just create functions that can be used to manage your objects, keeping them as plain objects
    export function publicMethod(obj) {
      privateFunction(obj);
    }
    
    function privateFunction(obj) {
      // ...
    }
    
    publicMethod(JSON.parse(localStorageStringValue));
    

    These approaches are fairly equivalent. Classes obviously allow for polymorphism and inheritance, while the function-based/imperative approach does not. Often you don't need these things, and just having a small library of related functions is simpler and more performant than classes.