将 javascript class 实例转换为普通对象保留方法

Convert javascript class instance to plain object preserving methods

我想将实例 class 转换为普通对象,而不丢失方法 and/or 继承的属性。例如:

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();
        this.name = 'Doe';
    }
    public getName() {
        return this.name;
    }
}
class PersonWorker extends Person {
    constructor() {
        super();
    }
    public report() {
        console.log('I am Working');
    }
    public test() {
        console.log('something');
    }
}
let p = new PersonWorker;
let jsoned = p.toJSON();

jsoned 应该是这样的:

{
    // 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 this.name},

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

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

这是否可能实现,如果可以,如何实现?

如果你想知道,我需要这个,因为我正在使用一个框架,不幸的是,它只接受一个对象作为输入,而我正在尝试使用 TypeScript 和 class 继承。

此外,我只进行了一次上述转换,因此性能不是需要考虑的问题。

如果编译器的目标选项设置为 es6,则由遍历对象属性组成的解决方案将不起作用。在 es5,通过遍历对象属性(使用 Object.keys(instance))的现有实现将起作用。

到目前为止,我有这个实现:

toJSON(proto?: any) {
    // ???

    let jsoned: any = {};
    let toConvert = <any>proto || this;

    Object.getOwnPropertyNames(toConvert).forEach((prop) => {
        const val = toConvert[prop];
        // don't include those
        if (prop === 'toJSON' || prop === 'constructor') {
            return;
        }
        if (typeof val === 'function') {
            jsoned[prop] = val.bind(this);
            return;
        }
        jsoned[prop] = val;
        const proto = Object.getPrototypeOf(toConvert);
        if (proto !== null) {
            Object.keys(this.toJSON(proto)).forEach(key => {
                if (!!jsoned[key] || key === 'constructor' || key === 'toJSON') return;
                if (typeof proto[key] === 'function') {
                    jsoned[key] = proto[key].bind(this);
                    return;
                }
                jsoned[key] = proto[key];
            });
        }
    });
    return jsoned;
}

但这仍然不起作用。结果对象仅包含所有 class 的所有属性,但仅包含 PersonWorker 的方法。 我在这里错过了什么?

这是 toJSON() 方法的实现。我们正在将属性和方法从当前实例复制到一个新对象,并排除不需要的方法,即 toJSON 和构造函数。

toJSON() {
    var jsonedObject = {};
    for (var x in this) {

        if (x === "toJSON" || x === "constructor") {
            continue;
        }
        jsonedObject[x] = this[x];
    }
    return jsonedObject;
}

我已经在 Chrome 中测试了 toJSON() 返回的对象,我发现该对象的行为方式与您预期的相同。

好吧,所以我的 OP 中的实现是错误的,而且这个错误简直是愚蠢的。

使用es6时的正确实现是:

toJSON(proto) {
    let jsoned = {};
    let toConvert = proto || this;
    Object.getOwnPropertyNames(toConvert).forEach((prop) => {
        const val = toConvert[prop];
        // don't include those
        if (prop === 'toJSON' || prop === 'constructor') {
            return;
        }
        if (typeof val === 'function') {
            jsoned[prop] = val.bind(jsoned);
            return;
        }
        jsoned[prop] = val;
    });

    const inherited = Object.getPrototypeOf(toConvert);
    if (inherited !== null) {
        Object.keys(this.toJSON(inherited)).forEach(key => {
            if (!!jsoned[key] || key === 'constructor' || key === 'toJSON')
                return;
            if (typeof inherited[key] === 'function') {
                jsoned[key] = inherited[key].bind(jsoned);
                return;
            }
            jsoned[key] = inherited[key];
        });
    }
    return jsoned;
}

这对我有用

const classToObject = theClass => {
  const originalClass = theClass || {}
  const keys = Object.getOwnPropertyNames(Object.getPrototypeOf(originalClass))
  return keys.reduce((classAsObj, key) => {
    classAsObj[key] = originalClass[key]
    return classAsObj
  }, {})
}

我经常重复 Alex Cory 的解决方案,但这就是我想出的。它期望作为函数分配给 class,并在 this.

上具有相应的绑定
const toObject = function() {
  const original = this || {};
  const keys = Object.keys(this);
  return keys.reduce((classAsObj, key) => {
    if (typeof original[key] === 'object' && original[key].hasOwnProperty('toObject') )
      classAsObj[key] = original[key].toObject();
    else if (typeof original[key] === 'object' && original[key].hasOwnProperty('length')) {
      classAsObj[key] = [];
      for (var i = 0; i < original[key].length; i++) {
        if (typeof original[key][i] === 'object' && original[key][i].hasOwnProperty('toObject')) {
          classAsObj[key].push(original[key][i].toObject());
        } else {
          classAsObj[key].push(original[key][i]);
        }
      }
    }
    else if (typeof original[key] === 'function') { } //do nothing
    else
      classAsObj[key] = original[key];
    return classAsObj;
  }, {})
}

然后,如果您使用的是 TypeScript,则可以将此接口放在应转换为对象的任何 class 上:

export interface ToObject {
  toObject: Function;
}

然后在你的 classes 中,不要忘记绑定 this

class TestClass implements ToObject {
   toObject = toObject.bind(this);
}

使用 Lodash

此方法不是递归的。

  toPlainObject() {
    return _.pickBy(this, item => {
      return (
        !item ||
        _.isString(item) ||
        _.isArray(item) ||
        _.isNumber(item) ||
        _.isPlainObject(item)
      );
    });
  }

这个解决方案会丢失方法,但是将class实例转换为对象是一个非常简单的解决方案。

obj = JSON.parse(JSON.stringify(classInstance))

已经有很多答案,但这是使用 spread syntax and de-structuring 对象最简单的答案:

const {...object} = classInstance