0

I can't figure out how to store objects that contain methods. If I use localStorage.setItem('inventory', JSON.stringify(hero.inventory));

and some of the items(objects) in the inventory have methods, I only get the properties with hero.inventory = JSON.parse(localStorage.getItem('inventory'));

how can you store and retrieve objects with all its properties and methods without getting the circular error?

1 Answers1

0

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 );
Community
  • 1
  • 1
Sirko
  • 72,589
  • 19
  • 149
  • 183
  • awesome thanks, altough there's a bug. it should be `c1.parse( JSON.parse( s ) );` – user3065579 Feb 11 '14 at 13:45
  • @user3065579 The error is more likely in the definition of `Countdown`. The parse method should not be on the prototype. I think it is cleaner to attach it to the constructor function itself, than to its prototype. – Sirko Feb 11 '14 at 13:52