0

I’m making a React App JavaScript game, and I am trying to figure out the best method for importing classes in a character select feature.

As there will be different characters used based on what characters the user chooses, I can’t just import the same classes and create new instances of the same classes.

How can I import classes in real time based on the users choices, and create new instances of said classes.

For example: When the user adds a warrior class character to their team, I want to import the warrior class, and create a new warrior instance like “const userWarrior = new Warrior(…)”

lsKakashi
  • 43
  • 5
  • Does this answer your question? [How can I conditionally import an ES6 module?](https://stackoverflow.com/questions/36367532/how-can-i-conditionally-import-an-es6-module) – Xiduzo Dec 02 '22 at 19:34
  • I don’t think so because the solution uses if statements, and if I have a large amount of classes to choose from to import that would be a really big if/else statement. And if I did use that, I’m still unsure of how I would declare a new instance of the class without knowing what the class was. – lsKakashi Dec 02 '22 at 19:41
  • 1
    you can also make a factory method for creating the class, check out https://refactoring.guru/design-patterns/factory-method. You could then create a new character by calling (for example) `const character = new Character(userChoice)` – Xiduzo Dec 02 '22 at 19:46
  • Interesting, I will try using this and see how it goes. Thanks for the input, I’ll be back with an update! – lsKakashi Dec 02 '22 at 20:04
  • Factory pattern was a good solution! There will still be a big if/else statement but at least it’s in another file out of the way. – lsKakashi Dec 03 '22 at 07:13

0 Answers0