Search code examples
javascriptstringclassobjectget

Get object class from string name in javascript


I would like to get an object from its name in Javascript. I'm working on an application which will need to load up some different context, I'm trying so to load different classes with the "inherit" jquery plugin. Everything works just fine, excepts that, when I need to instanciate a class I can't because I've only the name of the class and not the object directly.

Basically, I would like to find something like 'getClass(String name)'. Does anyone could help me ?


Solution

  • Don't use eval().

    You could store your classes in a map:

    var classes = {
       A: <object here>,
       B: <object here>,
       ...
    };
    

    and then just look them up:

    new classes[name]()