0
class Shape {}
let myClass = 'Shape';
new myClass();

This looks for a class myClass and fails, I have no idea how to get it to try and create a Shape class.

In PHP it would be simple:

class Shape {}
$myClass = 'Shape';
new $myClass();

How can I do this in JavaScript?

I've tried new window[myClass](), it doesn't work with ES6 classes.

  • _“I've tried `new window[myClass]()`, it doesn't work with ES6 classes.”_ — Yes, it does. Class declarations don’t become global properties automatically; you could theoretically still assign them: `globalThis.Shape = Shape`. But the much better approach is to use an Object (or a Map) to hold all your dynamically named classes: `const yourClasses = { Shape: class Shape{`…`} }; new yourClasses[myClass]();`. – Sebastian Simon Jan 16 '23 at 01:24
  • @SebastianSimon I can't go and change the structure of every page that uses it. Previously the person who wrote the code used eval(). Without going through the entire site and finding every page which may utilise it and changing the structure of each and every page to make sure every class is stored inside an object, what alternative is there? I could never have imagined something so simple would be so difficult. – I need herlp Jan 16 '23 at 01:43
  • Sounds like the previous person created quite a bit of tech debt for you to pay; and it’s likely that this is not the only problem in your code base. You’ll have to refactor the code anyway. Most IDEs have the functionality to search and replace in all files (usually `Ctrl` + `Shift` + `F` or so). If you have code like `new eval(myClass)`, why not search and replace it globally, e.g. with a regex like `new eval\((.*?)\)` → `theClasses[\g<1>]` (or whatever the syntax for the first capturing group is)? Yes, you’ll still have to take care of `theClasses` if you don’t want to stick with `eval`… – Sebastian Simon Jan 16 '23 at 02:16

0 Answers0