我想将实例类转换为普通对象,而不丢失方法和/或继承的属性。例如:
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 和类继承。
另外,我只进行了一次上述转换,因此性能不是需要考虑的问题。
如果编译器的目标选项设置为 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;
}
但这仍然不起作用。结果对象仅包含所有类的所有属性,但仅包含 PersonWorker
中的方法。我在这里错过了什么?
原文由 eAbi 发布,翻译遵循 CC BY-SA 4.0 许可协议
好的,所以我的 OP 中的实现是错误的,而且这个错误简直是愚蠢的。
使用
es6
时的正确实现是: