簡體   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

解析后如何將打印功能添加到對象? 有沒有一個優雅的解決方案?

您可以創建用於打印的原型並使用用於綁定的對象調用該方法。

 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

一個干凈的方法是添加一個函數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();

JSON 數據格式不支持函數(如果您從 JavaScript 對象生成一些 JSON,然后嘗試使用 C# 解析它,這將非常無用!)。

一個明智的方法是更改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
    }
    ...

然后你可以:

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

...這也將生成一個具有正確原型的對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM