重建从 localStorage 检索的对象函数
我使用 JSON.stringify
和 JSON.parse
从 localStorage
存储和检索对象。但是,JSON.stringify 似乎从对象中删除了实例函数。因此,在 JSON.parse 之后,我无法再调用 myObject.doSomething() 。我知道我可以手动附加此函数:myObject.doSomething = MyClass.prototype.myFunction
,但如果此操作在网络应用程序中重复多次,那就会很麻烦。人们通常如何在 JavaScript 中做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JSON 显然不保留函数本身,仅存储简单类型的变量。我在传递中解决这个问题的方法是在我的类中使用一个恢复方法,并且只需使用 JSON 中的数据调用该方法,以便使用属于该类的数据重新填充该类。
我已经在我的代码库中使用值对象(VO)设计模式广泛地完成了这项工作,并且它对我来说效果很好。不过需要注意的是,如果您尝试跨窗口通信,Ie7/Ie8 对这种方法不太友好。我记得我认为 IE7 没有为某些属性返回正确的“typeof”,因此当涉及跨窗口通信时,我在恢复过程中遇到了一大堆挑战。
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.