简体   繁体   English

打字稿:在另一个Class构造函数中创建Class实例的数组

[英]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.

相关问题 在实例方法的类构造函数中使用“ this”的打字稿问题 - Typescript issue using 'this' inside class constructor for instance method Undefined不是尝试在另一个类中创建一个类的新实例的构造函数 - Undefined is not a constructor trying to create new instance of one class inside another 使用构造函数参数实例化打字稿类实例 - instantiate typescript class instance with constructor parameters 从TypeScript创建Javascript类的实例 - Creating an instance of a Javascript class from TypeScript 引用存储在另一个类的数组中的类实例 - Referencing a class instance stored in an array in another class 创建空构造函数并在 class 中初始化数组时出现问题 - Problems creating an empty constructor, and initializing an array in a class Typescript中的模型类构造函数 - Model class constructor in Typescript TypeScript / JavaScript:<class> 不是构造函数</class> - TypeScript / JavaScript: <class> is not a constructor 如何将类构造函数的先前实例的参数传播到另一个实例 - How to spread the parameters of a previous instance of a class constructor to another instance 在实例对象内部的函数中获取类的实例(this)-Typescript / Angular - Get instance of class (this) in function inside instance object - typescript/angular
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM