Home > Blockchain >  Retrieve private methods of objects from localStorage
Retrieve private methods of objects from localStorage

Time:12-09

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,});

So my question is, is there a way to reassociate the private methods?

Is there a better approach altogether?

Thank you for your attention!

CodePudding user response:

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() {
    _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.

  • Related