Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS - Javascript create object instance from String

In my Node.Js application (server side) I have to create an object instance (that is a class, so with new MyClass()) but MyClass is a string.

Its possible to create object instance from a String ? I've see that in browser side I can use window, but here I'm on server side...

I will need this because I will now the name of the class at run time, so I can't instantiate this object in "code".

Moreover, I can have several classes that need to be created in this way. In short, I have a configuration file that explicit this kind of class, and I need to convert this string in a real JavaScript object.

like image 457
Mistre83 Avatar asked May 29 '16 09:05

Mistre83


2 Answers

With nodejs, window is "replaced" by global. So if your class is available in the global context, you can use global["ClassName"] to fetch it.

However, if you can, you may also consider the use of a dictionary of constructors. It is generally cleaner. Here is an example.

var constructors = {
   Class1: Class1,
   Class2: Class2
};

var obj1 = new constructors["Class1"](args);
like image 107
Quentin Roy Avatar answered Oct 18 '22 08:10

Quentin Roy


Do you mean

var myClass = Object.assign(new MyClass(), JSON.parse(classString));
like image 2
Jack Wang Avatar answered Oct 18 '22 06:10

Jack Wang