0

I have a constant which contains a list of classes:

const MY_LIST = [
    MyClass1,
    MyClass2,
    MyClass3
];

I am trying to loop over the list of classes and call method of each class. Like this:

for(const myClass of MY_LIST) {
    // this is where I try to dynamically create a class
    const my = new myClass();

    // this is where I am trying to call a method from dynamically created class
    my.someMethod();
}

Do you see anything wrong with this approach? Does this make sense?

4
  • Is there a specific problem you're having and trying to ask about? Did you try it? Commented Jun 14, 2021 at 0:55
  • I am trying to rewrite logic from PHP. In the PHP this is how it works. I am wondering if there is any better way in NodeJS. Commented Jun 14, 2021 at 0:58
  • I don't see anything wrong with this. What I don't understand is why you didn't just try it first and post if you had an actual problem you could ask about. That would have taken you far less than the 25 minutes you've waited so far. Commented Jun 14, 2021 at 1:05
  • I wanted to know if there is any better approach in nodejs for using dynamically created classes. Commented Jun 14, 2021 at 1:09

1 Answer 1

1

Do you see anything wrong with this approach?

No, there is nothing wrong with this approach. It will work just fine.

Does this make sense?

If that's what you want to do, this is an appropriate way to create a set of instances from a list of Classes.

You haven't shown the real problem you're trying to solve so we can't comment on potentially better or different ways to solve the real problem.

Sign up to request clarification or add additional context in comments.

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.