我希望将实例类转换为普通对象,同时不会失去方法和/或继承属性。例如:
这是否有可能实现,如果可以,怎样实现?
如果你想了解的话,我需要这个是因为我正在使用一个框架,它只接受对象作为输入,而我正在尝试使用TypeScript和类继承。
此外,我只需要进行一次上述转换,因此性能不是要考虑的问题。
通过迭代对象属性来解决将无法在编译器的目标选项设置为
到目前为止,我有这个实现:
但是这仍然没有起作用。生成的对象只包括所有类的属性,但仅包括
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
的方法。我在这里缺少了什么?
toJSON() {return Object.keys(this).reduce((obj, key) => {obj[key] = this[key]; return obj;}, {});}
- Louay Alakkades6
进行目标设置时,使用Object.keys
的旧方法将无法工作。 - eAbitoJSON
也是一个特殊的方法名称,如果存在,将由JSON.stringify
使用以获得对象的字符串表示形式。 - Heretic Monkey