localObject = JSON.parse( localStorage.getItem( '_myStorage' ) ); // "{'a':1, 'b':2}" → {a:1, b:2}
localStorage.setItem( '_myStorage', JSON.stringify( localObject ) );
var ObjectStorage = function ObjectStorage( name, duration ) { var self, name = name || '_objectStorage', defaultDuration = 5000; // , , // , // duration ( ) if ( ObjectStorage.instances[ name ] ) { self = ObjectStorage.instances[ name ]; self.duration = duration || self.duration; } else { self = this; self._name = name; self.duration = duration || defaultDuration; self._init(); ObjectStorage.instances[ name ] = self; } return self; }; ObjectStorage.instances = {}; ObjectStorage.prototype = { // type == local || session _save: function ( type ) { var stringified = JSON.stringify( this[ type ] ), storage = window[ type + 'Storage' ]; if ( storage.getItem( this._name ) !== stringified ) { storage.setItem( this._name, stringified ); } }, _get: function ( type ) { this[ type ] = JSON.parse( window[ type + 'Storage' ].getItem( this._name ) ) || {}; }, _init: function () { var self = this; self._get( 'local' ); self._get( 'session' ); ( function callee() { self.timeoutId = setTimeout( function () { self._save( 'local' ); callee(); }, self._duration ); })(); window.addEventListener( 'beforeunload', function () { self._save( 'local' ); self._save( 'session' ); }); }, // , (clearTimeout( storage.timeoutId )) timeoutId: null, local: {}, session: {} };
var storage = new ObjectStorage; storage.local = {a:4, b: {c:5}}; storage.session = {a:7, b: {c:8}}; b = storage.local.b; bc = {d:6};
var storage = new ObjectStorage; console.log( storage ); /* { _name: ..., duration: ..., local: {a:4, b: {c: {d: 6}}}, session: {a:7, b: {c :8}} } */
new ObjectStorage( '_myStorage', 1000 );
new ObjectStorage( null, 1000 );
var storage = new ObjectStorage; storage.duration = 2000;
storage.local = {a:{}} storage.local.ab = 5; // a = storage.local.a; ab = 5; //
Source: https://habr.com/ru/post/144998/
All Articles