The usual way to do this is to put your constructors in an object and then view them on that object using the generated string key:
let ctors = {
AnObject: class {
constructor(name) {
this.name = name;
}
}
};
let className = "An" + "Object";
let p2 = new ctors[className]("name2");
console.log("p2 name: " + p2.name);
Live copy on Babel REPL
Alternatively, and I just do it here, I do not recommend , you can use eval
:
class AnObject {
constructor(name) {
this.name = name;
}
}
let className = "An" + "Object";
let p2 = new (eval(className))("name2");
console.log("p2 name: " + p2.name)
Live copy on Babel REPL
Or a little more verbose, but perhaps clearer:
let className = "An" + "Object";
let ctor = eval(className);
let p2 = new ctor("name2");
console.log("p2 name: " + p2.name)
eval
great if you are in full control of the rows you are evaluating. But it usually overflows with well-structured code.
source
share