[ACCEPTED]-Get object class from string name in javascript-get

Accepted answer
Score: 18

Don't use eval().

You could store your classes 1 in a map:

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

and then just look them up:

new classes[name]()
Score: 5

JavaScript: Call Function based on String:

 function foo() { }


Score: 3

You can perfectly use eval() without a security 3 risk:

var _cls_ = {}; // serves as a cache, speed up later lookups
function getClass(name){
  if (!_cls_[name]) {
    // cache is not ready, fill it up
    if (name.match(/^[a-zA-Z0-9_]+$/)) {
      // proceed only if the name is a single word string
      _cls_[name] = eval(name);
    } else {
      // arbitrary code is detected 
      throw new Error("Who let the dogs out?");
  return _cls_[name];

// Usage
var x = new getClass('Hello')() // throws exception if no 'Hello' class can be found

Pros: You don't have to manually manage 2 a map object.

Cons: None. With a proper regex, no 1 one can run arbitrary code.

More Related questions