How? Getting class by name within instance for another class

Let’s imagine we have a class

class MyClass {...}

In another place of our code we have the following class:

class Parser {
run(classNameString) {
let instance = new classNameString();
}
}

We need:

  • to get class by name;
  • to create instance of this class;
  • to do these actions within another object;

I found out the following solution

class Parser {
run(classNameString) {
let instance = new moduleRootclassNameString;
}
}

var moduleRoot = this;

But it seems to me too ugly.

Any ideas?

One approach is to maintain an available classes map object, like the following:

class MyClass { 
  hello() { 
    console.log('Hello!'); 
  }
};

const classes = { 
  MyClass
};

class Parser {
  run(classNameString) {
    const myClass = new classes[classNameString]();
    console.log(myClass.hello());
  }
}

parser = new Parser();
parser.run('MyClass');

Another is to use eval (which is usually recommended against).