简体   繁体   中英

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.

But I cannot access in a "generic" way any attributes on the class.

this[key] = object[key];

Is there a way to do it?

This is my object assignement:

p1: Person = new Person({ name: 'John Doe' });
p2: Person = new Person({ age: 2, height: 180 });

This is my Person 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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM