Can I save object prototype in local storage?

2.6k views Asked by At

I have JS object with custom methods as prototype (e. g. Foo.prototype.myAwesomeMethod). If I load my object in a localStorage and get it later I'll loose these methods.

var foo = new Foo()
console.log(foo.myAwesomeMethod()) // WIN

localStorage.setItem('foo', foo)

foo = localStorage.getItem('foo')
console.log(foo.myAwesomeMethod()) // FAIL...

Is it possible to save the prototype of the object in the localStorage ? If not, how to properly re-instantiate the class?

1

There are 1 answers

3
AudioBubble On

you can try this

function Foo() {
  this.bar = 1;
}
Foo.prototype.myAwesomeMethod = function () {
  return "And the winner is " + this.bar;
}
var foo;

window.onload = function () {
  foo = new Foo();
  foo.bar = 3;
  console.log(foo.myAwesomeMethod()); // "And the winner is 3"
  var test = JSON.stringify(foo); //localStorage.setItem('foo', foo);
  foo = JSON.parse(test); // = localStorage.getItem('foo');
  foo.__proto__ = new Foo(); // <--------------
  console.log(foo.myAwesomeMethod()); // "And the winner is 3"
});

EDIT: my previous code was untested and didn't work, this is the working code