简体   繁体   English

用函数解析对象

[英]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.一个干净的方法是添加一个函数deserialize作为原型,它接受一个对象并将所有属性分配给实例。

 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#!). JSON 数据格式不支持函数(如果您从 JavaScript 对象生成一些 JSON,然后尝试使用 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.一个明智的方法是更改Car构造函数,以便它可以接受一个对象作为第一个参数。

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. ...这也将生成一个具有正确原型的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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