Skip to content Skip to sidebar Skip to footer

How To Instantiate A Class From A String In Javascript

I'm in a weird situation that i need to instantiate a new Class with a string stored in a variable but even i'm sure the class name is correct i get an error that given class name

Solution 1:

One possibility is to use eval.

classFoo {
    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:

classFoo {
    constructor(){
        console.log('Foo!');
    }
};

classGoo {
    constructor(){
        console.log('Goo!');
    }
};

// construct dict object that contains our mapping between strings and classes    const dict = newMap([['Foo', Foo], ['Goo', Goo]]);

// make a class from a stringconst 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:

  1. 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).

  2. 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

constclassFactory = (_className)=>{
    let dynamicConstructor = {};
    dynamicConstructor[_className] = class {
        constructor(_code){
            this.code = _code;
            console.log(`${_className} initialised with code: ${_code}!`);

        }
    };
    return dynamicConstructor[_className];
}

constMyClass = classFactory("Foo");
let fooInstance2 = newMyClass(123);

console.debug(fooInstance2);

Post a Comment for "How To Instantiate A Class From A String In Javascript"