Dynamically initialize an instance with the ES6 JavaScript class

How to dynamically initialize an object with class ES6?

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);
+4
source share
1 answer

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)

evalgreat if you are in full control of the rows you are evaluating. But it usually overflows with well-structured code.

+5
source

Source: https://habr.com/ru/post/1610085/


All Articles