[英]How to JSON.stringify a user-defined class in Javascript?
JSON.stringify()適用於文字對象,例如:
var myObjectLiteral = {
a : "1a",
b : "1b",
c : 100,
d : {
da : "1da",
dc : 200
}
};
var myObjectLiteralSerialized = JSON.stringify(myObjectLiteral);
myObjectLiteralSerialized被賦值,“{”a“:”1a“,”b“:”1b“,”c“:100,”d“:{”da“:”1da“,”dc“:200}}”as as預期。
但是,如果我用這樣的ctor定義類,
function MyClass() {
var a = "1a";
var b = "1b";
var c = 100;
var d = {
da : "1da",
dc : 200
};
};
var myObject = new MyClass;
var myObjectSerialized = JSON.stringify(myObject);
然后將myObjectSerialized設置為空字符串“”。
我認為原因是因為類版本最終成為實例化類的原型,這使得它的屬性由原型“擁有”,而JSON將只對字符串化實例對象myObject所擁有的道具。
是否有一種簡單的方法可以將我的類轉換為JSON字符串,而無需編寫一堆自定義代碼?
您的MyClass
沒有在正在構造的對象上設置任何屬性。 它只是為構造函數創建局部變量。
要創建屬性,請在構造函數中this
設置屬性,因為this
引用了新對象:
function MyClass() {
this.a = "1a";
this.b = "1b";
this.c = 100;
this.d = {
da : "1da",
dc : 200
};
}
此外,你通常不會屬性的添加.prototype
構造函數中的對象。 它們只需要添加一次 ,並將在構造函數創建的對象之間共享。
function MyClass() {
this.a = "1a";
this.b = "1b";
this.c = 100;
this.d = {
da : "1da",
dc : 200
};
}
MyClass.prototype.toJSON = function() {
return; // ???
}
MyClass.prototype.equals = function(other) {
if(other != null && other.prototype == this) {
if(this.a == other.a
&& this.b == other.b
&& this.c == other.c
&& this.d.da == other.d.da
&& this.d.dc == other.d.dc)
return true;
}
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.