三个时间相同的类实例,但实例值略有不同

时间:2019-05-31 11:00:13

标签: javascript typescript oop

我有一个带有一堆实例变量的类。现在,我想创建该类的三个实例,其中大多数值相同,但只有其中几个具有不同的值。如果没有(深层)克隆一个实例,是否有一些可能性或概念可以做到这一点?这些实例的子类是最好的方法吗?

我曾考虑过克隆一个实例,但是我的类是深层嵌套的,这似乎效率很低。

这是我上的课。就我而言,大多数变量保持不变,但在这三个实例中shortDescription的值不同。

export default class Event extends Base {
  public id!: number;
  public afterbuyId!: number;
  public shopId!: number;

  public name!: string;
  public sellingPrice!: number;
  public taxRate!: number;
  public level!: number;
  public shortDescription!: string;
  public startDate!: Date;
  public startTime!: Date;
  public endDate!: Date;
  public endTime!: Date;
  public quantityCheckProduct!: boolean;
  public active!: boolean;

  public venues: Venue[] = [];
  public bundles: Bundle[] = [];
  public paymentMethods: PaymentMethod[] = [];
  public deliveryMethods: DeliveryMethod[] = [];
  public categories: Category[] = [];
}

忽略事实,变量是公共的。

1 个答案:

答案 0 :(得分:0)

Ok, I already found a solution. I'll return an array of objects consisting of the needed variables and their values:

public generateRequestObject(): any {
    return [
      {
        "name": this.name,
        "sellingPrice": this.sellingPrice
      },
      {
        "name": `MP ${this.name}`,
        "sellingPrice": this.sellingPrice
      }
    ];
  }