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

A guide on detecting overflow in a React functional component

I am in search of a way to determine if a div contains overflowing text and display a "show more" link if it does. While researching, I came across an insightful Stack Overflow answer on checking for overflow in a div. The answer suggests implementing a fu ...

A guide on storing multiple values in a JSON format using Java

Currently, I am working on fetching a list of values from the JDBC database with multiple columns. To tackle this issue, I decided to create a JSON object structured like the example below: { "Results 1": { "IP": "192.1 ...

Tips for Extracting Real-Time Ice Status Information from an ArcGIS Online Mapping Tool

My goal is to extract ice condition data from a municipal website that employs an ArcGIS Online map for visualization. I want to automate this process for my personal use. While I have experience scraping static sites with Cheerio and Axios, tackling a sit ...

Can you identify the issue with my database file?

Here is the content from my database.js file: const MongoClient = require('mongodb').MongoClient; const db = function(){ return MongoClient.connect('mongodb://localhost:27017/users', (err, database) => { if (err) return co ...

Issue: "StoreController Undefined" error in Python Flask + Angular application

In the python flask application that I have built with Angular JS for the front end, there are three main files. app.py import json import flask import numpy as np app = flask.Flask(__name__) @app.route("/") def index(): ...

Traversing a JavaScript array with multiple dimensions containing markers created with Google Maps APIs

I have a single array where I store all of the Google Maps marker objects. Currently, I am working on creating a function to remove all markers from the map that are in the array, but I'm facing issues with the loop. First, I add each marker to the a ...

Checking the Json response with Java

Can someone help me extract the textType and taxAmount values from the JSON response below? { "taxExempt": false, "billingAddress": { "addressLine1": "Millers Rd", "addressLine2": "", "city": "Bengaluru", "postalCode": "560052", "sta ...

What is the interpretation of this error message and is there a solution I can apply to resolve

Utilizing the tweepy API, I am streaming specific information and saving it into a CSV. While tweets are being stored successfully, an error message keeps appearing: ('failed ondata', 'coercing to Unicode: need string or buffer, NoneType fou ...

Guide to automatically updating a table with AJAX requests

My task involves utilizing AJAX to request a random string consisting of 10 numbers from an asp page. The numbers must be delimited by "||" and displayed in a table format. The table is designed to showcase only the top 10 results, with each new row addin ...

Breaking down a large JSON array into smaller chunks and spreading them across multiple files using PHP pagination to manage the

Dealing with a large file containing over 45,000 arrays can be challenging, especially on a live server with high traffic. To address this issue, I used the array_chunk($array, 1000) function to divide the arrays into 46 files. Now, my goal is to access a ...

combine multiple keys into a single element with angular-translate

Within my application, I am retrieving translation keys from a single cell within a database table and dynamically displaying them on a settings page. While most entries will have just one key in the display object, there are some that contain multiple key ...

Error message: "An issue occurred: Unable to access undefined properties (specifically, borderRadius) in MUI react."

I recently created a navigation bar with an integrated search bar component. The styling for my search component was done using MUI styled from @emotion/styled in MUI library, where I applied a borderRadius: theme.shape.borderRadius. However, I encountere ...

I am attempting to assign a default value to a TextField by retrieving data from a GetMapping call in React, however, the value is not being successfully set

I am facing an issue with setting a default value for a TextField in my code. Even though I am trying to populate it with data from a GetMapping call, the value is not being set as expected. Here is the JSON response I receive from the API call: { "id": 1 ...

Utilizing the `this` keyword within a click handler that is passed through an intermediary function

If I initially have a click event handler in jQuery set up like this jQuery('#btn').click(_eventHandler); And handling the event as follows function _eventHandler(e){ jQuery(this).text('Clicked'); } Does the this keyword serve a ...

Load Angular scripts only when needed

I need to develop an application that can dynamically register new Angular Controllers obtained from a script. This application should load the minimum necessary scripts at startup and then fetch additional scripts as needed from other modules. Here' ...

Warning: The DataTables alert has been triggered for table ID DimStatus. It is indicating that an unknown parameter, 'Code', has been requested for row 0 and column 0 during the initialization

https://i.stack.imgur.com/yEpSp.pngI am encountering an error while attempting to display my data in a datatable. The structure of my table is as follows: [Table("DimStatus", Schema = "dmg")] public class PolicyState { [Key] ...

Troubleshooting issue with JavaScript sorting function failing to arrange elements in ascending

I'm having trouble sorting numbers in ascending order using JavaScript. Here's the code snippet: <h2>JavaScript Array Sort</h2> <p>Click the button to sort the array in ascending order.</p> <button onclick="myFunctio ...

Tips for accessing cart values when navigating to a different view in AngularJS

Hi, I'm currently working on a project involving a shopping cart. The project includes various categories with different products within each category. When adding a product to the cart from one category, it displays correctly. Likewise, adding anot ...

Is there a way to specifically use nl2br() for just one row when sending everything to an array?

In our database, there are a total of 20 rows. One of the rows is structured as follows: 1) cool text 2) not really 3) something else? The rest of the rows contain one line of data each. When it comes to outputting a single row with line breaks, we ut ...

Is it a common occurrence for AJAX applications utilizing POST requests to encounter issues in Internet Explorer?

After some investigation, I have come across a bug in Internet Explorer that is causing intermittent failures for users running my application. This bug exists within the HTTP stack of IE and impacts all applications utilizing POST requests from this brows ...