如何在Javascript中JSON.stringify用户定义的类?

Tom*_*nes 3 javascript serialization json

JSON.stringify()适用于文字对象,例如:

var myObjectLiteral = {
    a : "1a",
    b : "1b",
    c : 100,
    d : {
        da : "1da",
        dc : 200
    }
};
var myObjectLiteralSerialized = JSON.stringify(myObjectLiteral); 
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

然后将myObjectSerialized设置为空字符串"".

我认为原因是因为类版本最终成为实例化类的原型,这使得它的属性由原型"拥有",而JSON将只对字符串化实例对象myObject所拥有的道具.

是否有一种简单的方法可以将我的类转换为JSON字符串,而无需编写一堆自定义代码?

use*_*716 12

MyClass没有在正在构造的对象上设置任何属性.它只是为构造函数创建局部变量.

要创建属性,请this在构造函数中设置属性,因为this引用了新对象:

function MyClass() {
    this.a = "1a";
    this.b = "1b";
    this.c = 100;
    this.d = {
        da : "1da",
        dc : 200
    };
}
Run Code Online (Sandbox Code Playgroud)

此外,您通常不会向构造函数.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;
}
Run Code Online (Sandbox Code Playgroud)