1

How can I call a javascript class from a string? Is that possible at all? One solution I didn't find that good was to store the initialization of the classes in an array and then address the object via the key. But are there other possibilities?

What I want

const classNameAsString = "HelloWorld";

class HelloWorld {
  constructor() {
    console.log("Hello World")
  }
}

const hW = new ${classNameAsString}(); // that is wrong and would throw an error
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
  • have you looked into `eval`? – Iłya Bursov Oct 07 '22 at 14:24
  • What do you mean by "call a `class`"? A `class` isn't a function... – Dai Oct 07 '22 at 14:24
  • @Dai (yeah they are) - `typeof (class Example{})` – evolutionxbox Oct 07 '22 at 14:25
  • @evolutionxbox A class constructor is a `function`, and a `class` is sugar over a `function` too, but that's not the same thing as having `class` function objects being functors... – Dai Oct 07 '22 at 14:26
  • You can store the class in an object and use bracket notation – Xion 14 Oct 07 '22 at 14:26
  • @IłyaBursov I dont use eval! But thank you for your comment! – Maik Lowrey Oct 07 '22 at 14:28
  • @Dai I edit. I mean initialisation. Thanks for sugesstion – Maik Lowrey Oct 07 '22 at 14:29
  • Did the OP already try any global scope? e.g. for the global `window` scope ... `const hW = new window[classNameAsString]();`. In environments with e.g. module scope (but not only there) the OP is free of importing class-constructors and assign it to an e.g. `classes` object which then could be accessed and instantiated like `const hW = new classes[classNameAsString]();` – Peter Seliger Oct 07 '22 at 14:32
  • @Xion14 You are right! I already read that in stackoverflow. But i will know if exists other solution to do this. But thank you for your good sugesstion! – Maik Lowrey Oct 07 '22 at 14:33
  • @PeterSeliger Your comment sounds very good! Unfortnatly the question was close because your idea would be a good answer. – Maik Lowrey Oct 07 '22 at 14:35
  • @MaikLowrey ... my comment is as good an answer as it was without the closed thread. – Peter Seliger Oct 07 '22 at 14:37
  • The linked question [has a similar answer](https://stackoverflow.com/a/5187620/989920) – evolutionxbox Oct 07 '22 at 14:38
  • @PeterSeliger hmm, you are right ;-) – Maik Lowrey Oct 07 '22 at 14:38
  • @evolutionxbox Merci for the link! I will try. The only problem would be that i didnt want use the class in the global scope because it is only a helperClass which i will use in a VueJs app. – Maik Lowrey Oct 07 '22 at 14:40

0 Answers0