[英]How to assign new Class object through factory method but in a "generic" way?
I'm trying to create a class where I can pass optional parameters and through a factory method it assigns the values to the corresponding class attributes.我正在尝试创建一个 class,我可以在其中传递可选参数,并通过工厂方法将值分配给相应的 class 属性。
But I cannot access in a "generic" way any attributes on the class.但我无法以“通用”方式访问 class 上的任何属性。
this[key] = object[key];
Is there a way to do it?有办法吗?
This is my object assignement:这是我的 object 作业:
p1: Person = new Person({ name: 'John Doe' });
p2: Person = new Person({ age: 2, height: 180 });
This is my Person class:这是我的人 class:
export class Person {
name: string = '';
age: number = 0;
height: number = 0;
constructor(data: Object) {
this.factory(data);
}
factory(object: Object) {
for (const key in object) {
if (object.hasOwnProperty(key)) {
this[key] = object[key]; // <-- HERE IS MY PROBLEM
}
}
}
}
I put my code on Stackblitz我把我的代码放在Stackblitz上
There is an elegant solution for this.有一个优雅的解决方案。 Add an indexer and use a more concrete parameter type.
添加索引器并使用更具体的参数类型。 Look at this:
看这个:
export class Person {
name: string = '';
age: number = 0;
height: number = 0;
[key: string]: any;
constructor(data: Partial<Person>) {
this.factory(data);
}
factory(object: Partial<Person>) {
for (const key in object) {
this[key] = object[key];
}
}
}
Update : That should work even without indexer:更新:即使没有索引器也应该可以工作:
factory(object: Partial<Person>) {
Object.assign(this, object);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.