简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM