The usual way to do this is to put your constructors on an object, and then look them up 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's REPL
Alternately, and I'm just being complete here not recommending it, 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's REPL
Or a bit more verbose, but possibly clearer:
let className = "An" + "Object";
let ctor = eval(className);
let p2 = new ctor("name2");
console.log("p2 name: " + p2.name)
eval
is fine as long as you're in complete control of the strings you're evaluating. But it's usually overkill in well-structured code.