samedi 9 janvier 2016

Convert javascript class instance to plain object preserving methods

Vote count: 0

I want to convert an instance class to plain object, without losing methods and/or inherited properties. So for example:

class Human {
    height: number;
    weight: number;
    constructor() {
        this.height = 180;
        this.weight = 180;
    getWeight() { return this.weight; }
    // I want this function to convert the child instance
    // accordingly
    toJSON() {
        // ???
        return {};
class Person extends Human {
    public name: string;
    constructor() {
        super(); = 'Doe';
    public getName() {
class PersonWorker extends Person {
    constructor() {
    public report() {
        console.log('I am Working');
    public test() {
let p = new PersonWorker;
let jsoned = p.toJSON();

jsoned should look like this:

    // from Human class
    height: 180,
    weight: 180,
    // when called should return this object's value of weight property
    getWeight: function() {return this.weight},

    // from Person class
    name: 'Doe'
    getName(): function() {return},

    // and from PersonWorker class
    report: function() { console.log('I am Working'); },

    test: function() { console.log('something'); }

Is this possible to achieve, and if so, how?

In case you're wondering, I need this because I am using a framework that, unfortunately, accepts as input only a json object, whereas I am trying to use typescript and class inheritance.

asked 57 secs ago

This entry passed through the Full-Text RSS service - if this is your content and you're reading it on someone else's site, please read the FAQ at

Convert javascript class instance to plain object preserving methods

Aucun commentaire:

Enregistrer un commentaire