Dynamically choose class from string - “MyClassName” -> MyClassName [duplicate]

北城余情 提交于 2019-12-23 12:34:48

问题


I use babel.js traspiler to write ES6 code.

I have a string containing class name. I want a class that I can instantiate. How?

I tried:

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

Any ideas?


回答1:


You Can:

Since with BabelJS you have to transpile to an ES5 module loader, it would be as simple as (depending on the module format you've specified at transpile time):

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

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

In an ES6 environment a class is just syntactic sugar for a function, so there is no reason you cannot do:

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

And load it like so:

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

But in doing so you've just broken the major feature modules give you in the first place.

You Should:

Create a factory class. In the majority of cases, the amount of classes you can instantiate is finite. You should create a factory function which gives you a class instance based on a string:

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

Which would be used as:

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

Obviously you could expand on that to use a Map instead of a string of if statements, but you get the idea.



来源:https://stackoverflow.com/questions/32866478/dynamically-choose-class-from-string-myclassname-myclassname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!