pckben pckben - 3 days ago 6
Javascript Question

reconstruct object functions retrieved from localStorage

I'm using

JSON.stringify
and
JSON.parse
to store and retrieve objects from
localStorage
. However, it appears that
JSON.stringify
strips out the instance functions from the object. Thus, after
JSON.parse
, I can no longer call
myObject.doSomething()
. I know that I can attach this function manually:
myObject.doSomething = MyClass.prototype.myFunction
, but that'll be troublesome if this action is repeated many times in the web app. How do people normally do this in JavaScript?

Answer

JSON obviously does not hold onto the functions themselves is only stores simple typed variables. The way I have addressed this in the pass is to be a restore method in my class and simply call that method with the data from JSON so as to re-populate the class with the data that belongs in it.

I have done this extensively with the Value Object ( VO ) design pattern in my code base and it has worked quite well for me. Just a word of a caution though, Ie7/Ie8 are not terribly friendly with this approach if you try to communicate across windows. As I recall I think it is IE7 that does not return the right "typeof" for some properties so I ran into a whole bunch of challenges in my restore when cross-window communication was involved.

Comments