在sessionStorage中保存Javascript对象 [英] Save Javascript objects in sessionStorage

查看:112
本文介绍了在sessionStorage中保存Javascript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SessionStorage和LocalStorage允许在Web浏览器中保存键/值对。该值必须是一个字符串,并且保存js对象并不简单。

SessionStorage and LocalStorage allows to save key/value pairs in a web browser. The value must be a string, and save js objects is not trivial.

var user = {'name':'John'};
sessionStorage.setItem('user', user);
var obj = sessionStorage.user; // obj='[object Object]' Not an object

现在,您可以通过以下方式避免此限制:将对象序列化为JSON,然后反序列化它们以恢复对象。但Storage API始终通过 setItem getItem 方法。

Nowadays, you can avoid this limitation by serializing objects to JSON, and then deserializing them to recover the objects. But the Storage API always pass through the setItem and getItem methods.

sessionStorage.setItem('user', JSON.stringify(user));
var obj = JSON.parse(sessionStorage.getItem('user')); // An object :D

我可以避免这种限制吗?

Can I avoid this limitation?

我只想执行这样的事情:

I just want to execute something like this:

sessionStorage.user.name; // 'John'
sessionStorage.user.name = 'Mary';
sessionStorage.user.name // 'Mary'

我试过 defineGetter defineSetter 拦截调用的方法,但这是一项繁琐的工作,因为我必须定义所有属性而我的目标不是了解未来的属性。

I have tried the defineGetter and defineSetter methods to intercept the calls but its a tedious job, because I have to define all properties and my target is not to know the future properties.

推荐答案

您可以使用Web Storage API提供的访问器,也可以编写包装器/适配器。从你声明的问题来看,defineGetter / defineSetter听起来像编写包装器/适配器对你来说太多了。

Either you can use the accessors provided by the Web Storage API or you could write a wrapper/adapter. From your stated issue with defineGetter/defineSetter is sounds like writing a wrapper/adapter is too much work for you.

老实说,我不知道该告诉你什么。也许你可以重新评估你对什么是荒谬的限制的看法。 Web Storage API就是它应该是的一个键/值存储。

I honestly don't know what to tell you. Maybe you could reevaluate your opinion of what is a "ridiculous limitation". The Web Storage API is just what it's supposed to be, a key/value store.

这篇关于在sessionStorage中保存Javascript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆