Get object class from string name in javascript

不打扰是莪最后的温柔 提交于 2019-12-23 08:55:03

问题


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 ?


回答1:


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]()



回答2:


JavaScript: Call Function based on String:

 function foo() { }
 this["foo"]();



回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/5646279/get-object-class-from-string-name-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!