2

I need to create a new class objects in loop where I can provide a dynamic name of this class, e.g. I have class "tree":

export default class ParentClass {
    // ...
}

export default class Thomas extends ParentClass {
    // ...
}

export default class Paul extends ParentClass {
    // ...
}

and loop:

const workers = ['Thomas', 'Paul'];
for (const worker of workers) {
    const h = new <worker>();
    // do something with this object
}

Is it possible to do this? Project using NodeJS with Express.js.

2
  • Does all the names in the workers-array correspond to an existing class? Commented Sep 9, 2019 at 11:07
  • @John Yes, I'm not allowing to use "name" of non-existing class. Commented Sep 9, 2019 at 11:11

2 Answers 2

3

This is possible, either you can put the class constructors right in the array:

const workers = [Thomas, Paul];
for (const workerConstructor of workers) {
  const h = new workerConstructor();
  // do something with this object
}

Or, put them in a map so you can access them using a string key:

const classMap = {
  'Thomas': Thomas,
  'Paul': Paul
}

const workers = ['Thomas', 'Paul'];
for (const workerKey of workers) {
  const h = new classMap[workerKey]();
  // do something with this object
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could do something like this:

const workers = ['Thomas', 'Paul'];
for (const worker of workers) {
    let c;
    eval("c=new "+worker+"()");
    // do something with this object
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.