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 ?
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]()
JavaScript: Call Function based on String:
function foo() { }
this["foo"]();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With