Rick Grendel
Rick Grendel

Reputation: 302

How to call a class from a javascript string

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 :)

Upvotes: 0

Views: 952

Answers (2)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

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'];

Upvotes: 1

Jeremy Thille
Jeremy Thille

Reputation: 26390

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

Upvotes: 2

Related Questions