[英]Typescript: Creating Array of Class instance inside another Class constructor
Whats is the best way of creating a class instance from JSON which has an array of other class as a member 什么是从JSON创建类实例的最佳方法,JSON具有其他类的数组作为成员
class Someclass {
memList: Mem[];
constructor(data: any) {
for(let i=0;i<data.mems.length;i++) {
this.memList.push(new Mem(data.mems[i]));
}
}
//methods
...
}
export class Mem {
// Mem class with members
}
Json
{
mems: [
{//here mem properties},
{},
{}
],
someOtherProp: {}
}
What is the general practice followed in this scenario? 在这种情况下遵循的一般惯例是什么?
Looping inside the constructor and creating a new instance is considered a good approach? 在构造函数内部循环并创建新实例被认为是一种好方法吗?
Inside Mem class if it's creating a list of other class objects, will it slow down creating a class instance of Someclass? 在Mem类内部,如果要创建其他类对象的列表,是否会减慢创建Someclass的类实例的速度?
class Someclass {
memList: Mem[];
constructor(data: any) {
this.memList = data.mems.map(m => new Mem(m));
}
//methods
...
}
... is a nice concise way to do what you want, though your way is fine too - if you added this.
...是一种很好的简洁方法,可以执行所需的操作,尽管您的方法也很好-如果您添加了
this.
before memList
. 在
memList
之前。 Don't worry about slowing down construction of the class, unless you have an enormous data set, but then you probably have other problems anyway. 除非您拥有庞大的数据集,否则不必担心放慢类的构造,但是无论如何您可能还会遇到其他问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.