2

Is there a way in nodejs to instantiate class object with variable class name. I am trying the below snippet, it doesn't work though.

let className = "hello"; 
let object = new [className]();

EDITED I have multiple classes, out of those multiple classes I will get a subset(Array of String) as Input from another service and I have to call main function of those subset classes.

// Multiple classes = ["first", "second", ..............., "twenty"]; 

let subset_class_names = ["first", "three", "five"]; 

for (let aClass of subset_class_names) { 
    let object = new [aClass](); 
    object.main(); 
}
2
  • Why? I dont know any usecase for this Commented Jan 13, 2018 at 11:04
  • I have multiple classes, out of those multiple classes I will get a subset as Input and I have to call main function of those subset classes. </br> // Multiple classes = ["first", "second", ..............., "twenty"]; let subset_class_names = ["first", "three", "five"]; for (let class of subset_class_names) { let object = new [class](); object.main(); } Commented Jan 13, 2018 at 11:53

3 Answers 3

2

Instead of iterating over class names, why not iterate over the classes itself?

class One {
  constructor(){
    console.log("One constructed");
  }
}


class Two {
  constructor(){
    console.log("Two constructed");
  }
}

const classes = [One, Two];

for(const aClass of classes)
  new aClass();

Sign up to request clarification or add additional context in comments.

1 Comment

I will get class names as an input from another service, and then iterate and instantiate the objects. This is not possible in my case directly.
1

You can try this using window

var className = 'hello'
var obj = new window[className];

3 Comments

I am getting this error : ReferenceError: window is not defined
ok that generally works in client side, since you are using it on node.js look this window is a browser thing that doesn't exist on Node. If you really want to create a global, use global instead:
0

I think most programming problems become easy when you know how to use data structures. In this case all you need is a Map of class names to classes themselves.

class One {
  constructor(){
    console.log("One constructed");
  }
}


class Two {
  constructor(){
    console.log("Two constructed");
  }
}

class Three {
  constructor(){
    console.log("Three constructed");
  }
}


const classes = new Map()
classes.set("one", One);
classes.set("two", Two);
classes.set("three", Three);

let subset_class_names = ["one", "two"]; 

for (let aClass of subset_class_names) {
  const theClass = classes.get(aClass);
  if (theClass) new theClass();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.