且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用JSON创建从对象类型继承的对象?

更新时间:2023-11-03 12:06:46

我不这么认为。如果我是你,我会在Person类上创建一个函数来从JSON对象初始化。

I don't imagine so. I'd create a function on the Person class to initialise from a JSON object if I were you.

function Person() {
    this.loadFromJSON = function(json) {
        this.FirstName = json.FirstName;
    };
}

如果你不知道JSON对象事先代表什么类,也许在JSON中添加一个额外的变量。

If you didn't know what class the JSON object was representing beforehand, perhaps add an extra variable into your JSON.

{ _className : "Person", FirstName : "Mike" }

然后有一个'builder'函数解释它。

And then have a 'builder' function which interprets it.

function buildFromJSON(json) {
    var myObj = new json["_className"]();
    myObj.loadFromJSON(json);
    return myObj;
}






更新:既然你说该类是您无法更改的第三方库的一部分,您可以使用原型扩展该类,或者编写一个仅在外部填充该类的函数。


Update: since you say the class is part of a third-party library which you can't change, you could either extend the class with prototyping, or write a function which just populates the class externally.

例如:

Person.prototype.loadFromJSON = function(json) {
    // as above...
};

function populateObject(obj, json) {
    for (var i in json) {
        // you might want to put in a check here to test
        // that obj actually has an attribute named i
        obj[i] = json[i];
    }
}