pckben pckben - 1 year ago 72
Javascript Question

reconstruct object functions retrieved from localStorage

I'm using

to store and retrieve objects from
. However, it appears that
strips out the instance functions from the object. Thus, after
, I can no longer call
. 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download