title: JavaScript object that saves/loads its state
body: <p>I'd like to create a Javascript object that can save and load its state (to local storage).</p>
  
  <p>This is the basic pattern I'm using:</p>
  
  <pre><code>var obj = function () {
  
      // private members
      //
  
      return {
  
          // public members
  
          load: function () {
              this.state = JSON.parse(localStorage.getItem('obj'));
  
              if (this.state === null) {
                  this.state = {
                      name: 'foo'
                  };
              }
          },
  
          save: function () {
              localStorage.setItem('obj', JSON.stringify(this.state));
          }
      };
  }();
  
  // load state
  obj.load();
  console.log(obj.state.name);
  
  // save state
  obj.state.name = 'bar';
  obj.save();
  </code></pre>
  
  <p>But there's one thing that annoys me about this pattern: I have to access the object's persistent properties through the 'state' property.</p>
  
  <p>How can I rewrite this so I can use the object in a more natural way, like:</p>
  
  <pre><code>// load state
  obj.load();
  console.log(obj.name);
  
  // save state
  obj.name = 'bar';
  obj.save();
  </code></pre>
  
  <p>This is a very simple 'state', but the solution has to work for a complex state object with nested objects, arrays etc., so simply adding a 'name' property to my object is not what I'm after.</p>