0

I am making a nodejs server. I have made a system where I need to dynamically load different classes. The name of the classes are in string. It looks like this:

var classname = "foo"; // this is the name of the class I want to call.

var bar = new classname //classname needs to be foo in this example.

I already tried window[classname] but this wont work because this is nodejs so there is no window to work with.

Thank you for reading :)

samAlvin
  • 1,643
  • 8
  • 33
Rick Grendel
  • 193
  • 1
  • 2
  • 14

2 Answers2

2

eval("new " + classname) but "beware, eval is evil", etc.

Jeremy Thille
  • 25,196
  • 9
  • 41
  • 59
  • Wow thank you for the link that was very useful. In my case I cant use eval because the classname will come from the url so its not very save. – Rick Grendel Sep 19 '17 at 11:29
1

The better approach is to make use of a JSON object. To achieve that , you can always have a key:value JSON object where the key corresponds to your variable. See the example below. The variable classname is actually a key of the JSON object obj then you can easily reference that to simulate as if you are creating a new class:

var obj = {
   classname : 'foo'
};

var bar = new obj['classname'];
Ankit Agarwal
  • 29,658
  • 5
  • 35
  • 59