9

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.

Malik Khalil
  • 6,454
  • 2
  • 39
  • 33
Mistre83
  • 2,677
  • 6
  • 40
  • 77
  • I think that the factory pattern is what you are seeking for: essentialjsdesignpatterns/book/#factorypatternjavascript. – Alberto De Caro May 29 '16 at 09:19
  • 1
    Possible duplicate of [How to execute a JavaScript function when I have its name as a string](http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string) – nwk May 29 '16 at 09:41

2 Answers2

14

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);
Quentin Roy
  • 7,677
  • 2
  • 32
  • 50
  • This is exactly what i was in mind! My idea was to create an handler to manage all the classes in a Object like you showed me the factory. But I did not think it was possible to call new on it. You saved my life :D – Mistre83 May 29 '16 at 09:33
1

Do you mean

var myClass = Object.assign(new MyClass(), JSON.parse(classString));
Jack Wang
  • 462
  • 7
  • 17