Get object class from string name in javascript

I would like to get an object on its behalf in Javascript. I am working on an application that will need to be loaded into some other context, I am trying to load different classes using the "inherit" jquery plugin. Everything works fine, except that when I need to initialize a class, I cannot, because I only have the class name and not the object directly.

Basically, I would like to find something like getClass (String name). Can anybody help me?

+6
source share
3 answers

Do not use eval() .

You can save your classes on the map:

 var classes = { A: <object here>, B: <object here>, ... }; 

and then just view them:

 new classes[name]() 
+10
source

JavaScript: string based call function :

  function foo() { } this["foo"](); 
+5
source

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
source

Source: https://habr.com/ru/post/885798/


All Articles