[ACCEPTED]-Get object class from string name in javascript-get
Accepted answer
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]()
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.
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.