开发者

Get object class from string name in javascript

开发者 https://www.devze.com 2023-02-25 18:13 出处:网络
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

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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号