javascript 从javascript中的字符串名称获取对象类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5646279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get object class from string name in javascript
提问by Celero
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.
我想在 Javascript 中从它的名称中获取一个对象。我正在开发一个需要加载一些不同上下文的应用程序,我正在尝试使用“继承”jquery 插件加载不同的类。一切都很好,除了当我需要实例化一个类时我不能,因为我只有类的名称而不是直接的对象。
Basically, I would like to find something like 'getClass(String name)'. Does anyone could help me ?
基本上,我想找到类似“getClass(String name)”的东西。有没有人可以帮助我?
回答by Felix Kling
Don't use eval()
.
不要使用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]()
回答by Sjoerd
回答by ceremcem
You can perfectly use eval()
without a security risk:
您可以完美使用eval()
而没有安全风险:
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.
缺点:没有。使用适当的正则表达式,没有人可以运行任意代码。
回答by wong2
Do you mean this?
你是这个意思吗?
function Person(name){
this.name = name;
}
function getClass(str_name, args){
return new (window[str_name])(args);
}
var wong2 = getClass("Person", "wong2");
alert(wong2.name); // wong2