4

How to init an object dynamically with ES6 class?

class AnObject{
    constructor(name) {
    this.name = name;
   }
}
let p1 = new AnObject("name1");
console.log("p1 name: " + p1.name);
var className = "An" + "Object";
let p2 = new className("name2"); // Dynamically init an object?
console.log("p2 name: " + p2.name);
Sudarshan Kalebere
  • 3,813
  • 3
  • 34
  • 64
EES
  • 1,584
  • 3
  • 20
  • 38
  • 1
    It's no different than in ES5 - `AnObject` is just a function, and you have to get that function by its name before calling `new`. Using ES6 syntax for the class makes zero difference. – Bergi Oct 03 '15 at 10:49
  • 1
    @Bergi: Yeah, this is probably a duplicate. Although there is *one very slight* difference: If you're at global scope, you can't use the class from the global object, because class identifiers at global scope aren't added to the global object, even though they're global variables. (As with `let` and `const` at global scope.) – T.J. Crowder Oct 03 '15 at 10:52

1 Answers1

6

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875