Enhance your JavaScript skills by deserializing objects and seamlessly integrating new methods

Currently in my Javascript code, I am utilizing localStorage. Since objects cannot be directly stored in it, I am using JSON.stringify to serialize them before saving.

Within localStorage, I am storing the entire game state, where some of the sub-objects contain methods.

However, when retrieving these objects with JSON.parse, the methods are no longer present - which is expected behavior. Storing objects with methods in the browser would not be ideal.

What is the most effective way to reattach these methods to the object so that it functions as it did originally?

Would setting up something like

savedObj.prototype = MyClass.prototype;

be a suitable solution or am I overlooking something?

Answer №1

Perhaps you could try implementing something similar to this:

Javascript

function MyCustomClass(data) {
    if (typeof data === 'string') {
        this.data = JSON.parse(data);
    } else {
        this.data = {};
    }

    this.addContent = function (element) {
        element.appendChild(document.createTextNode(this.toJSON()));
    }
}

MyCustomClass.prototype = {
    display: function () {
        console.log(this.toJSON());

        return this;
    },
    update: function (key, value) {
        this.data[key] = value;

        return this;
    },
    toJSON: function () {
        return JSON.stringify(this.data);
    }
};

var myCustomClass1 = new MyCustomClass();

myCustomClass1.update('key', true);
myCustomClass1.display();

localStorage.myDataSave = myCustomClass1.toJSON();

var myCustomClass2 = new MyCustomClass(localStorage.myDataSave);

myCustomClass2.display();
myCustomClass2.addContent(document.body);

Check out the jsFiddle here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Understanding the process of retrieving a data value from HTML in an AngularJS directive

I'm a beginner with Angular and I'm trying to pass some data to my angular directive from the template. <div class="col-md-6" approver-picker="partner.approverPlan.data" data-pickerType="PLAN"></div> I h ...

Encountered a 404 error while utilizing the Java - Angular web service

Encountering an error 404 in Firebug when attempting to send an object from Angular to a Java controller using JSON. While the backend in Java is able to receive the message, Angular is unable to find the specified path. Consequently, there is an issue wit ...

Unable to retrieve the user ID from a Discord username using Discord JS

let string = `${args[1]} ${args[2]}` console.log(string) const idofuser = client.users.cache.find((u) => u.username === `${string}`).id I am facing an issue with DiscordJS where it says "cannot read property 'id' of undefined" when trying to ...

Is the history object automatically passed to child components within the Router in react-router-dom?

Is it normal for the Router component to automatically pass down the history object to child components? To showcase this concept, consider the following code snippet: App.js ; const App = () => { return ( <> <h1>Hello</h1&g ...

The pdf2json encountered an error when attempting to process a PDF file sent via an HTTP

I am encountering an issue while attempting to extract information from PDF files using a nodejs script. Upon running the program, I encounter the following error: Error: stream must have data at error (eval at <anonymous> (/Users/.../node_modules/ ...

Error encountered while rendering HTML template with Django and AngularJS due to TemplateSyntaxError

Hello, I am new to Angular and Django. I have built a Django webpage and am attempting to display values from a basic AngularJS app and controller tutorial using my HTML template. However, I keep encountering an error in the index.html file when trying to ...

Secondary Form Checkbox Input

Presently, I am working with a dynamic form-checkbox input element. <b-form-group label="Skills"> <b-form-checkbox-group v-model="form.selected" :options="options"/> </b-form-group> However, I am looking to enhance this functionalit ...

Customizing the "Actions" Dropdown in APEX Interactive Grid

Is there a way to modify the choices available in the Selection section of a Row Actions Menu in Apex? I managed to alter the options in the Line Menu, but I'm facing challenges when trying to make changes in the Selection Menu. The Selection Menu i ...

Exploring the power of React's useState and useEffect hooks with JSON data

Just starting out with React. The task I'm tackling involves fetching data from an API (provided in JSON format) and updating the setNavItems with the retrieved JSON response. However, when attempting to iterate over the results using navItems.map, n ...

The npm outdated -g command is producing an error message that states "Unable to read the length property of undefined"

I am currently facing an issue while trying to check the version status of my npm installed global packages. When I run the command npm outdated -g --depth=0 in the terminal, I encounter the following error: npm ERR! Cannot read property 'length&apos ...

Randomly loading Json files in Ionic is a great way to keep your

I have a div using *ngFor which loads values from a JSON file. I want to load values from different JSON files randomly each time the div is loaded. Is there a way to achieve this using Math.random() or any other methods? html file <div class= ...

Display loading images using the Bxslider plugin

Currently, I have implemented a Bxslider on my website with the following HTML markup: <div class="slide"> <a target="_blank" href="#"><img src="image.jpg"/></a> </div> <div class="slide"> <a target="_blank" href= ...

Retrieve telephone number prefix from Cookies using React

Being able to retrieve the ISO code of a country is possible using this method: import Cookies from 'js-cookie'; const iso = Cookies.get('CK_ISO_CODE'); console.log(iso); // -> 'us' I am curious if there is a method to obt ...

Exploring an alternative perspective on successful login in angular.js

Today was the beginning of my project to convert a website to angular.js. The main page is served by index.html and includes ng-view for other views such as login and signup. Working closely with a backend developer, I have successfully integrated a rest c ...

Attributes required are not functional on mobile devices

Good day! I have encountered an issue with the required attribute on a form on my website. It seems to be working perfectly on my browser, but not on mobile devices. Has anyone else experienced difficulties with jQuery, JavaScript, or Node packages? <f ...

Getting the value of a JSON object in CodeIgniter can be easily achieved by using the appropriate

My current project involves using the codeigniter framework to build a website. I am making an AJAX request with jQuery to retrieve data from the server. I have experimented with two different methods of receiving the data: one in a PHP associative array a ...

"Encountered an undefined error with the title property of this.state.project in the Wordpress API

I'm currently working on a project that involves a Backend Wordpress and a front-end React setup. However, I've encountered an issue when attempting to retrieve the title.rendered from the JSON Data. This error is displayed: TypeError: this.sta ...

Unable to convert JavaScript object to C# through deserialization

In order to pass a model from the controller action to the view, I included a list of objects and converted it into a JavaScript object to facilitate displaying markers on Google Maps. My goal is to send the selected object (selected marker) back to the co ...

Escaping latitude and longitude coordinates using PHP

I am looking to include longitude and latitude values in a json file. However, the current code I have escapes the values and adds quotation marks. Example of json output{"votes":["{\"lat\":\"51.426799\",\"lng\":\"-0.331 ...

What methods can be used to broaden configuration variables within VSCode using an extension?

I attempted to develop an extension for vscode that requires reading the pasteImage.parth variable from the ./vscode/settings.json file { "pasteImage.path": "${workspaceRoot}/assets/images" } In my attempt to retrieve the variable us ...