Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8976733
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T19:12:46+00:00 2026-06-15T19:12:46+00:00

I’d like to create a Javascript object that can save and load its state

  • 0

I’d like to create a Javascript object that can save and load its state (to local storage).

This is the basic pattern I’m using:

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();

But there’s one thing that annoys me about this pattern: I have to access the object’s persistent properties through the ‘state’ property.

How can I rewrite this so I can use the object in a more natural way, like:

// load state
obj.load();
console.log(obj.name);

// save state
obj.name = 'bar';
obj.save();

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T19:12:47+00:00Added an answer on June 15, 2026 at 7:12 pm

    If you don’t care which properties get loaded/saved then you can simply copy all from state into self. For example, after reading into var state (instead of this.state since you don’t want state to be a part of this anymore): for(x in state) this[x] = state[x];

    similarly, you’d save out: var state = {}; for(x in this) state[x] = this[x]

    However, if you want to have a pre-defined list, then I’d recommend: var fields = ['name', 'zip', 'age'];

    And then use for(x in fields) this[x] = state[x] to load and for(x in fields) state[x] = this[x]; to save.

    Sorry it’s a bit pieced together, but I hope you can follow what I mean 🙂

    EDIT: Added full example per OPs request.

    An example of a full solution using this technique is as follows:

    var obj = function () {
    
        // private members
        //
    
        return {
    
            // public members
    
            load: function () {
                var state = JSON.parse(localStorage.getItem('obj'));
    
                if(state == null) state = { name: 'foo' };
    
                for(x in state) this[x] = state[x];
            },
    
            save: function ()
            {
                var state = {};
    
                // check if it's a function.  This version taken from underscorejs
                var isFunction = function(obj) {
                    return !!(obj && obj.constructor && obj.call && obj.apply);
                };
    
                for(x in this)
                {
                   if(isFunction(this[x])) continue; // skip functions
    
                   state[x] = this[x];
                }
    
                localStorage.setItem('obj', JSON.stringify(state));
            }
        };
    };
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
I have a small JavaScript validation script that validates inputs based on Regex. I
I am trying to render a haml file in a javascript response like so:
I know there's a lot of other questions out there that deal with this
Does anyone know how can I replace this 2 symbol below from the string
I'm trying to create an if statement in PHP that prevents a single post
I used javascript for loading a picture on my website depending on which small

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.