Short answer: you can't.
Longer answer:
You can only store strings inside localStorage
. That's why you use JSON.stringify()
and JSON.parse()
in the first place.
See How to serialize & deserialize Javascript objects? for ways to circumvent this.
Or your object can include a constructor/method, which, if given all non-method properties will reconstruct the full object with all the methods.
Very basic example:
function Countdown( start ) {
this.start = start;
this.ticksCounted = 0;
}
Countdown.prototype.tick = function(){
this.start -= 1;
this.ticksCounted += 1;
}
Countdown.parse = function( param ) {
// get a basic object
var result = new Countdown();
// append all values
for( var key in param ) {
if( param.hasOwnProperty( key ) ) {
result[ key ] = param[ key ];
}
}
// return result
return result;
}
And the respective (de)serialization:
var c1 = new Countdown( 10 );
c1.tick();
console.log( c1 );
var s = JSON.stringify( c1 );
console.log( s );
var c2 = Countdown.parse( JSON.parse( s ) );
console.log( c2 );