Reputation: 302
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
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