Adjusting the prototype of a JavaScript object in real-time

Is there a way to dynamically change object prototype in JavaScript in order to fully recover an object previously saved using JSON, including its behavior?

Currently, one solution is to create a new object and copy the data from the JSON-recovered object to it. However, this approach may not be ideal.

(Check out this code on JSFiddle)

function Obj() {
    this.D = "D";
    this.E = "E";
    this.F = "F";

    this.toString = function () {
        return this.D + " * " + this.E + " * " + this.F;
    };

    this.copy = function (anotherObj) {
        for (var property in anotherObj) {
            if (isDef(anotherObj[property]) && isDef(this[property])) {
                this[property] = anotherObj[property];
            }
        }
    }
}
;

$(document).ready(function () {
    var str = $.toJSON(new Obj());
    $("#result").append("<p>JSON: " + str + "</p>");
    var obj = new Obj();
    obj.copy($.parseJSON(str));
    $("#result").append("<p>Recovered obj: " + obj.toString() + "</p>");
});

function isDef(variable)
{
    return typeof variable !== undefined;
}

Answer №1

Utilizing various JS libraries can simplify the process.

For instance, those working with jQuery may prefer using the jQuery.extend() method rather than a custom copy function:

var obj = $.extend(new Obj(), $.parseJSON(str));

Check out the modified jsFiddle here.

UPDATE: With insights from this discussion, I successfully ensured that the restored object retained its nested functionalities. Take a look at the revised jsFiddle.

The key approach involves utilizing prototypes over properties and ensuring that the object retrieved from JSON (essentially data) is passed as the first argument to $.extend():

function Obj2() {
    this.A = "A";
}
Obj2.prototype.toString = function() {
    return this.A;
};

function Obj() {
    this.A = new Obj2();
    this.D = "D";
    this.E = "E";
    this.F = "F";
}
Obj.prototype.toString = function() {
    return this.A.toString() + " * " + this.D + " * " + this.E + " * " + this.F;
};

var str = $.toJSON(new Obj());
$("#result").append("<p>JSON: " + str + "</p>");
var obj = jQuery.extend($.parseJSON(str), new Obj());
$("#result").append("<p>Recovered obj: " + obj.toString() + "</p>");

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

Having trouble with Angular JS $scope.$apply due to an interpolation error displaying "TypeError: Converting circular structure to JSON"?

I have created a specialized angular directive shown below: dirs.directive('sectionInfo', function(){ return { restrict: 'E', templateUrl: 'partials/section-home.html', transclude: true, co ...

Adjust the contents of an HTTP POST request body (post parameter) upon activation of the specified POST request

Is there a way to intercept and modify an HTTP Post Request using jQuery or JavaScript before sending it? If so, how can this be achieved? Thank you. ...

Using useCallback with an arrow function as a prop argument

I'm having trouble understanding the code snippet below <Signup onClick={() => {}} /> Upon inspecting the Signup component, I noticed the implementation of useCallback as follows const Signup = ({onClick}) => { const handleClick = us ...

The mongoimport jsonArray feature functions smoothly in a 64-bit build, but encounters an exception in a 32-bit environment

I have MongoDB standalone servers running in two different systems - one with Windows 8.1 Pro 64 Bit (MongoDB 2.6 64 Bit) and the other with Windows 7 Pro 32 Bit (MongoDB 2.6 32 Bit). Although mongoimport csv functions correctly on both systems, I encount ...

I tried implementing a progress bar for my JSON post and response, but unfortunately, it is not displaying as expected

I have successfully implemented JSON data posting to the server. However, I am facing an issue with integrating a progress bar to show the progress. The progress bar is not displaying at all despite the data being posted and response received. @Override ...

The curly braces in AngularJS are failing to display the values on the HTML page

After trying various articles and solutions to different questions, I am still unable to resolve my issue. I am working on a blank ionic project and it is running smoothly in my browser using ionic serve without any errors. However, instead of displaying ...

Retrieve and modify the various elements belonging to a specific category

I'm currently developing a chrome extension and I need to access all elements of this specific type: https://i.stack.imgur.com/sDZSI.png I attempted the following but was unable to modify the CSS properties of these elements: const nodeList = documen ...

How can I retrieve JSON data from within a function and show it on a textfield in Swift programming language?

I've been exploring how to parse JSON data into Swift, specifically attempting to display the area of my pincode in a text field. In order to do this, I've created three Swift files: mapview.swift, maphandler.swift, and mapmodel.swift. The issue ...

What is the best way to extract data from this file using jq?

Recently, I've delved into using jq and working with json files. My current endeavor involves parsing a specific file. While I'm attempting to accomplish this task using jq through the command line, I am open to exploring alternative methods for ...

Retrieve combination values through an AJAX request using ExtJS

My UI is developed using ExtJS, and I have a specific set of tasks that need to be executed when the page loads: Initiate an ajax call to the server to fetch a HashMap. Create a combobox within the main Panel on the page. var combo = Ext.create(' ...

What Causes the Undefined Value of "this" in Vue 3 Functions?

Here is a basic example of a component in Vue 3: <script> import { defineComponent } from 'vue' export default defineComponent({ name: 'Test', setup(){ return{ one, two } } }) function one(){ console. ...

Spotting the Visible Element; Detecting the Element in

Currently, my webpage has a fixed header and I am facing the challenge of dynamically changing the styling of the li elements within the navigation based on the user's scrolling position. To achieve this, I believe the most effective approach would b ...

Error: anticipated expression, received keyword 'if'

I'm facing an issue that I could really use some assistance with. I am trying to hide the "changeOrderUp" button when it's in the first row, and similarly, I want to hide the "changeOrderDown" button when it's in the last row. However, FireB ...

Python does not return the AJAX request back to JavaScript unless JQuery is not utilized

I have set up an XMLHTTPrequest in my javascript code to communicate with a flask location. Here's how I am doing it: var ourRequest = new XMLHttpRequest(); ourRequest.open("GET", "makeDiff") diff = ourRequest.send(); console.log(diff); Once the req ...

The instance is referencing "underscore" during render, but it is not defined as a property or method

I have experience as a skilled react developer, but I've taken over a vue.js project from another developer and managed it for quite some time. Regrettably, I haven't put in the effort to learn vue properly. When using lodash, I encountered an u ...

Using Javascript to transmit audio via a microphone

I am currently trying to use Selenium to simulate a user on a website that features audio chat. My goal is to emulate the user speaking through the microphone. While I have come across several resources discussing how to listen to the microphone in JavaSc ...

Navigate from Product Listing to Product Details Page by utilizing JSON data with ReactJS

I have successfully retrieved the initial level of JSON Data, which consists of objects/Product List. My objective is to implement a functionality where clicking on the "View Details" button will redirect to the respective product detail page, similar to ...

Obtain an array containing only the specific values of each object

Currently, I have the following code snippet: <db.collection>.find({ id : { $exists: true } }) This query retrieves all documents containing an id property. However, I am interested in transforming this result into an array that contains only the va ...

What methods are most effective for verifying user credentials in a web application using Node.js and AngularJS?

Currently, I am working on a project that involves using Node.js and MySQL for handling user data. I would like to leverage the user information stored in the MySQL database, but I am unsure about the most secure method for implementing user authentication ...

Incorporate geographical data from a JSON file into my Google Maps application

Hey there, I'm a newbie on this forum and could really use your expertise. I've put together an html5 page with Google maps using the API key from Google (My code is shown below), it's working fine with a central marker in place and loads pe ...