Dynamically select a class from a string - "MyClassName" & # 8594; Myclassname

I am using babel.js traspiler to write ES6 code.

I have a string containing the name of the class. I need a class that I can create. How?

I tried:

eval("MyClassName") -> :(
window["MyClassName"] -> :(

Any ideas?

+4
source share
1 answer

You can:

Since with BabelJS you have to go to the ES5 module loader, it will be just as easy (depending on the format of the module specified during the transfer):

const MyClassName = require("MyClassName");
const obj = new MyClassName();

However, this is not ES6, but transpiled ES5. Thus, your code will not work in real ES6 environments.

In ES6, a classis just syntactic sugar for a function, so there is no reason why you cannot:

// Class definition
class MyClassName { }
// Pollute global scope
(global || window).MyClassName = MyClassName;

:

const instance = new (window || global)["MyClassName"]();

, .

:

factory. , , . factory, :

import MyClassName from "./MyClassName"
class MyFactory {
    static getInstance(value) {
        if(value === "MyClassName") {
            return new MyClassName();
        }
        throw new Error(`Could not instantiate ${value}`);
    }
}

:

import MyFactory from "./MyFactory";
const instance = MyFactory.getInstance("MyClassName");

, Map if, .

+2

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


All Articles