How To Instantiate A Class From A String In JavaScript
Solution 1:
One possibility is to use eval
.
class Foo {
constructor(){
console.log('Foo!');
}
};
const foo = 'Foo';
const bar = eval(`new ${foo}()`);
console.log(bar);
You will have to evaluate the safety of using eval()
in your particular circumstances. If you know the origin of the string you are inserting into the code that you run eval()
on or you can sanitize it first, then it may be safe.
I personally would prefer a lookup table. If you have a known number of classes that you want to map by string, then you can make your own lookup table and use that. This has the advantage of there can be no unintended consequences if the string has weird stuff in it:
class Foo {
constructor(){
console.log('Foo!');
}
};
class Goo {
constructor(){
console.log('Goo!');
}
};
// construct dict object that contains our mapping between strings and classes
const dict = new Map([['Foo', Foo], ['Goo', Goo]]);
// make a class from a string
const foo = 'Foo';
let bar = new (dict.get(foo))()
console.log(bar);
If you were really going to go this route, you may want to encapsulate it in a function and then add error handling if the string is not found in the dict
.
This should be better than using the global or Window
object as your lookup mechanism for a couple reasons:
If I recall,
class
definitions in ES6 are not automatically put on the global object like they would with other top level variable declarations (Javascript trying to avoid adding more junk on top of prior design mistakes).So, if you're going to manually assign to a lookup object, you might as well use a different object and not pollute the global object. That's what the
dict
object is used for here.
Solution 2:
Similar to @jfriend00 ...
let className = "Foo";
let dynamicConstructor = {};
dynamicConstructor[className] = class {
constructor(){
console.log('Foo!');
}
};
let fooInstance = new dynamicConstructor[className]();
console.debug(fooInstance);
A sort of factory class constructor can also be used
const classFactory = (_className)=>{
let dynamicConstructor = {};
dynamicConstructor[_className] = class {
constructor(_code){
this.code = _code;
console.log(`${_className} initialised with code: ${_code}!`);
}
};
return dynamicConstructor[_className];
}
const MyClass = classFactory("Foo");
let fooInstance2 = new MyClass(123);
console.debug(fooInstance2);
Post a Comment for "How To Instantiate A Class From A String In JavaScript"