Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 283
Celero Avatar asked Apr 13 '11 08:04

Celero


3 Answers

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]()
like image 109
Felix Kling Avatar answered Sep 28 '22 11:09

Felix Kling


JavaScript: Call Function based on String:

 function foo() { }
 this["foo"]();
like image 33
Sjoerd Avatar answered Sep 28 '22 11:09

Sjoerd


You can perfectly use eval() without a security 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 a map object.

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

like image 38
ceremcem Avatar answered Sep 28 '22 11:09

ceremcem