I have multiple similar classes that I would like to call depending on the situation. I have a variable that will contain the name of the class I want to call.
So for example, I have this JavaScript code defining my classes.
class Parent {
constructor(id) {
// Do stuff...
}
}
class Child1 extends Parent {};
class Child2 extends Parent {}; // and many, many more...
Then I have this code which makes a new Child1 object.
var obj = new Child1(id);
However, I would like to be able to have the name of the class to call in a variable, and then call it with that, like so:
var className = "Child1"; //Or child 2, depending on scenario.
var obj = new className(id);
I know in PHP I can do $obj = new $className(id);
, which is exactly what I would like to do here in JavaScript.
I have read a few answers to some questions (this one for example) that said I could do this:
var obj = new window[className](id);
But doing that returned this error:
Uncaught TypeError: window[className] is not a constructor
Originally I had defined var className = "Child1"
within a function, and I thought the problem was that className
wasn't global, but when I tried to define className
globally, it still didn't work...