localStorage = { a: { b: 1 }, c: { d: 2 } } localStorage.ab = 3;
Object.defineProperty( window, 'objectLocalStorage', { // - get: function() { return {}; } });
window.objectLocalStorage.a = 1;
(function() { // , , // json var _objectLocalStorage = JSON.parse( localStorage.getItem( 'objectStorage' ) ) || {}, timer = null; // objectLocalStorage window // , localStorage, , Object.defineProperty( window, 'objectLocalStorage', { get: function() { // timer , // , localStorage , // // setTimeout >< , if( timer === null ) { timer = setTimeout( function(){ var stringified = JSON.stringify( _objectLocalStorage ); // : , // , if( stringified !== localStorage.getItem( 'objectStorage' ) ) { // localStorage.setItem( 'objectStorage', stringified ); } timer = null; }, 0); } return _objectLocalStorage; }, // , objectLocalStorage set: function( v ) { _objectLocalStorage = v; localStorage.setItem( 'objectStorage', JSON.stringify( _objectLocalStorage ) ); } } ); })();
objectLocalStorage = { a: 4, b: {c: 2} }; objectLocalStorage.bc = {d: 5}
console.log( objectLocalStorage ); // { a: 4, b: {c: {d: 5}} }
objectLocalStorage.ab = 5;
similarly _objectLocalStorage.ab = 5;
objectLocalStorage.ab = 5; // a = objectLocalStorage.a; ab = 5; //
It seems to me easier to read and write to a regular object, which is serialized to LS (by timeout and onbeforeunload), and deserialized when the application starts.
Source: https://habr.com/ru/post/143597/
All Articles