简体   繁体   中英

How to get JavaScript Objects with inheritance from JSON?

I'm currently trying to deepen my understanding of JavaScript, especially with regards to object inheritance. Therefore, as an exercise, I implement a client for an API. The API returns a JSON object consisting of lists of objects which I'd like to convert into lists of JavaScript objects with inheritance (to add common functions to the Parent object later on).

Here's a minimal example of what I currently do

json=JSON.parse('{"lista":[{"one":"","two":""},{"one":"","two":""}],"listb":[{"one":"","three":""},{"one":"","three":""}]}')

function Parent(parent) {
    this.one = parent.one;
}

function A(a) {
    Parent.call(this,a);
    this.two = a.two;
}

A.prototype = Object.create(Parent.prototype);
A.prototype.constructor = A;

function B(b) {
    Parent.call(this,b);
    this.three = b.three;
}

B.prototype = Object.create(Parent.prototype);
B.prototype.constructor = B;

function Collection(collection) {
    this.lista = (typeof collection.lista !== "undefined" ? collection.lista.map(function (a) {
        return new A(a)
    }) : undefined);
    this.listb = (typeof collection.listb !== "undefined" ? collection.listb.map(function (b) {
        return new B(b)
    }) : undefined);
}

collection=new Collection(json);

Is there a better way to create the JavaScript objects with inheritance from JSON?

Yan can use JSON.parse with receiver function something like this

json=JSON.parse('{"lista":[{"one":"","two":""},{"one":"","two":""}],"listb":[{"one":"","three":""},{"one":"","three":""}]}',
    function(k,v){
        if(k === "lista") return v.map(function(a){return new A(a);});
        if(k === "listb") return v.map(function(a){return new B(a);});
        return v;
    })

in this case json is object with two fields when field lista is array of A objects, and listb is array of B objects

Looks like you are coming from a C++/C#/Java world :)

Inheritance in JavaScript can be done the way you have written it, though all you gain from it is an added layer of complexity with no real gains.

Often, having a JSON based input as you have in the first line, JavaScripters simply use the elements directly as objects.

var collection={};
collection.lista = json.lista;
collection.listb = json.listb;

But, essentially your code of inheritance is fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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