简体   繁体   中英

Parsing an Object with 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

How can i add the print function to the object after the parse? Is there an elegant solution for this?

You could create a prototype for printing and call the method with an object for binding.

 function Car(name, year) { this.name = name; this.year = year; } Car.prototype.print = function() { // add prototype console.log(this.name + " " + this.year); // take this as reference to the instance }; var tesla = new Car("tesla", 2018); tesla.print(); tesla = JSON.parse(JSON.stringify(tesla)); console.log(tesla); Car.prototype.print.call(tesla); // borrow method from class, take own object

A clean approach is to add a function deserialize as prototype which takes an object and assign all properties to the 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();

The JSON data format does not support functions (which would be very unhelpful if you generated some JSON from a JavaScript object and then tried to parse it with C#!).

A sensible approach to this would be to change the Car constructor function so that it can accept an object as the first argument.

var Car = function(name, year) {
    if (typeof name === "object") {
        // use properties of `name` to set everything in this object
    } else {
        // Treat name and year as a string and number just like you are now
    }
    ...

Then you can:

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

… which will also generate an object with the correct prototype.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM