Analyzing an Object through Functions

var Car = function(name, year) {
    this.name = name;
    this.year = year;

    this.print = function() {
        console.log(name+" "+year);
    }
}

var tesla = new Car("tesla", 2018);
tesla.print();
tesla = JSON.parse(JSON.stringify(tesla));
console.log(tesla);
tesla.print(); // Uncaught TypeError: tesla.print is not a function

Is there a way to re-insert the print function into the object after it has been parsed? Any elegant solutions for this issue?

Answer №1

If you want to implement a cleaner method for printing in JavaScript, you can create a prototype for handling the functionality and then invoke the method using an object for binding.

function Car(name, year) {
    this.name = name;
    this.year = year;
}

Car.prototype.print = function() {            
    console.log(this.name + " " + this.year); 
};

var tesla = new Car("tesla", 2018);
tesla.print();
tesla = JSON.parse(JSON.stringify(tesla));
console.log(tesla);
Car.prototype.print.call(tesla);              

To enhance the approach further, you can include a function called deserialize as part of the prototype. This function can retrieve an object and assign all its properties to the current instance.

function Car(name, year) {
    this.name = name;
    this.year = year;
}

Car.prototype.print = function() {
    console.log(this.name + " " + this.year);
};

Car.prototype.deserialize = function(object) {
    Object.entries(object).forEach(([k, v]) => this[k] = v);
};

var tesla = new Car("tesla", 2018);
tesla.print();
tesla = JSON.parse(JSON.stringify(tesla));
console.log(tesla);
var tesla2 = new Car;
tesla2.deserialize(tesla);
tesla2.print();

Answer №2

When it comes to JSON data format, one important thing to note is that it does not support functions. This can create issues when attempting to parse JSON generated from a JavaScript object using C#!

A practical solution to this dilemma would involve modifying the Car constructor function to be able to accept an object as the initial argument.

var Car = function(name, year) {
    if (typeof name === "object") {
        // utilize properties from `name` to assign values in this object
    } else {
        // Treat name and year as strings and numbers, as is currently done
    }
    ...

Following this adjustment, you can do the following:

tesla = new Car( JSON.parse(JSON.stringify(tesla)) );

… which will result in an object with the correct prototype.

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

The combination of setInterval() and if(confirm()) is not possible in pure JavaScript

One day, I encountered a simple if(confirm()) condition like this: if(confirm('Some question')) { agreed_function(); } else { cancel_function(); } function agreed_function() { console.log('OK'); } function cancel_function( ...

Troubleshooting AngularJS POST Request Error with Request Body

I am a beginner in AngularJs and I am trying to make a post request to a server with enum form. Currently, I have the following JavaScript code: function completeTaskAction2($scope, $http, Base64) { $http.defaults.headers.common['Authorization'] ...

Unraveling JSON data within PHP after it has been passedbindParam

Decoding JSON Data with PHP I have a variable named jsonvar containing {"rating":"good"} After using the $.ajax code to send it to my PHP file (jsonproc.php), I'm unsure of how the PHP script should be structured. $.ajax({ url: &apo ...

An error occurred when attempting to search for 'length' using the 'in' operator in the context of the Datatables plugin and jQuery 1.11.3

I implemented the jQuery Datatables plugin in my tables for pagination, sorting, and searching functionalities. However, I am facing issues where the elements are not working properly, and the pagination occasionally fails to display. The Chrome console is ...

Utilizing Jquery to pass two classes along

I am looking for assistance on how to pass multiple classes within if-else statements and jQuery. My goal is to have both divs and divs2 change when the next button is clicked. Can someone please provide guidance on achieving this? --code not mine-- ...

How to retrieve a string value from an object in Express.Js by using the key value pair

I'm wondering about the proper way to retrieve a value from an object where the key value is a string. This involves sending data from the client side and receiving it on the backend using express.js. Example of data sent from the client side: var ...

jQuery AJAX Concurrent Event

I have encountered a problem similar to ones discussed on SO, but none exactly match my specific issue. Here's the situation: var x = 5; if( some condition ){ $.ajax({ url:"...", success: function(response){ x = respo ...

Guide on how to use a tooltip for a switch component in Material-UI with React

I am attempting to incorporate a tooltip around an interactive MUI switch button that changes dynamically with user input. Here is the code snippet I have implemented so far: import * as React from 'react'; import { styled } from '@mui/mater ...

What is causing the ESLint error when trying to use an async function that returns a Promise?

In my Next.js application, I have defined an async function with Promise return and used it as an event handler for an HTML anchor element. However, when I try to run my code, ESLint throws the following error: "Promise-returning function provided t ...

“What is the most effective way to verify the presence of an element within a numerical array using Twig

If we have an array stored in a variable (let's name it arr) in Twig and it looks like this: foo: [ { title: 'foo', id: 1 }, { title: 'bar', id: 2 }], bar: [ { some: 23, required: true }, { some: 12, ...

Utilizing Google APIs to split a route among multiple locations

I am facing a scenario where A laundry company operates from one shop location. The laundry company has 3 trucks available (n trucks). The laundry company needs to deliver washed clothes to multiple locations (n locations). https://i.sstatic.net/ULup8.pn ...

Is there an issue with JQM plugin due to jQuery's append() function?

I am just starting to learn about jQuery mobile as I develop an app using it. Whenever I click on the Add_details button, I want to add dynamic input fields only once. After saving, if I click on the Add_details button again, I need to append more dynamic ...

Emerald: Fresh alert for numerous attributes

After updating jade to the latest version, I started seeing a message in the console that says: You should not have jade tags with multiple attributes This change was mentioned as a feature here 0.33.0 / 2013-07-12 Hugely more powerful error reporting ...

Highcharts JavaScript - Sankey Graph Axis Orientation

As I work on developing a Sankey Diagram using the Highcharts JS library, I have encountered an issue with setting the axis. Can anyone advise whether it is feasible to utilize xAxis and yAxis in a Sankey diagram? I attempted to define the axis as shown b ...

Is adding ng-click in a template counterproductive to the concept of MV* architecture?

When working with AngularJS, you may come across instances where the ng-click handler is directly connected to an HTML element like <a> or <button>. Take for example the snippet below (borrowed from an Angular homepage sample), where the click ...

What is the most effective way to utilize zoom with an Orthographic projection?

I'm attempting to utilize THREE.OrbitControls for zooming in an orthographic projection, but I'm not achieving the desired outcome. I believe it may be possible to adjust the viewSize that is multiplied by left, right, top, and bottom to achieve ...

Enhance the table using Django URL tag along with JQuery

I am currently working on a table that is being populated with user details and I would like to include a Django URL tag within the row, extracting the primary key in the process. Here is an example of what I am trying to achieve: function putTableData(re ...

Form submissions are not saving checkbox answers

As a beginner, I'm struggling to save the checkbox answers on the page after submission. The code below is quite lengthy (checkboxes start at 314). I have a feeling that I might be missing a piece of code, but I just can't seem to pinpoint what i ...

What steps can be taken to enable CORS on an existing server that was created with createServer function?

The following code snippet is what I currently have: var gqlServer =require('./server.js') var server=gqlServer() var port = process.env.PORT||5000 server.listen({port:port}, ()=> console.log(` ...

Leveraging the power of node pkg to generate standalone executables while configuring npm

I have successfully used pkg to create an executable file for my node js application. Everything is working fine in that aspect. However, I am also utilizing the config module to load yaml configuration files based on the environment. During the packaging ...