javascript - Dynamically choose class from string - "MyClassName" -> MyClassName -
this question has answer here:
i use babel.js traspiler write es6 code.
i have string containing class name. want class can instantiate. how?
i tried:
eval("myclassname") -> :( window["myclassname"] -> :(
any ideas?
you can:
since babeljs have transpile es5 module loader, simple (depending on module format you've specified @ transpile time):
const myclassname = require("myclassname"); const obj = new myclassname();
however not es6, transpiled es5. code not work in true es6 environments.
in es6 environment class
syntactic sugar function, there no reason cannot do:
// class definition class myclassname { } // pollute global scope (global || window).myclassname = myclassname;
and load so:
const instance = new (window || global)["myclassname"]();
but in doing you've broken major feature modules give in first place.
you should:
create factory class. in majority of cases, amount of classes can instantiate finite. should create factory function gives class instance based on string:
import myclassname "./myclassname" class myfactory { static getinstance(value) { if(value === "myclassname") { return new myclassname(); } throw new error(`could not instantiate ${value}`); } }
which used as:
import myfactory "./myfactory"; const instance = myfactory.getinstance("myclassname");
obviously expand on use map
instead of string of if
statements, idea.
Comments
Post a Comment