local storage - how to hydrate a javascript object -


i have javascript object (userobject) populate on 1 page, add object localstorage using json.stringify

now on next page, rehydrate userobject values localstorage on first page.

the userobject global variable declared once, in shared/common javascript.

but using current logic, login page stores username , userid in userobject, window.location.href page redirection. data in userobject being cleared (assuming old object being washed away, in favor of new object on new page).

the question is, how rehydrate new userobject on main page values localstorage.

here how loading locastorage

localstorage.setitem('userobject', json.stringify(userobject)); 

this thinking on rehydrating userobject

userobject = localstorage.getitem('userobject'); 

but upon viewing userobject... string or values, doesn't recreate object , fill values, long string...

localstorage can't know how original object. need explicitly call json.parse().

userobject = json.parse(localstorage.getitem('userobject')); 

update:

note functions never serialized or supported in json. because not reliable reconstruct functions or prototypes generated "source code", because a) prototypes aren't captured in json , b) functions may have access closures.

in order have methods on rehydrated object prototype, proceed thisway:

// user constructor function  function user() {    }    user.prototype.isvalid = function () {    return true;  };    user.prototype.isadmin = function () {    return this.name === "admin";  };    // create , serialize object  var usera = new user();  usera.name = "admin";    var copy = json.parse(json.stringify(usera));    // rehydrate functions on prototype  var userb = new user();  (var prop in copy) {    if (object.prototype.hasownproperty.call(copy, prop)) {      userb[prop] = copy[prop];    }  }    console.log(userb.isadmin());


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -