Home Instantiate class object with variable class name in nodejs
Reply: 2

Instantiate class object with variable class name in nodejs

Rahul Chawla
1#
Rahul Chawla Published in 2018-01-13 10:50:34Z

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(); 
}
Sajeetharan
2#
Sajeetharan Reply to 2018-01-13 11:01:11Z

You can try this using window

var className = 'hello'
var obj = new window[className];
Jonas W.
3#
Jonas W. Reply to 2018-01-13 14:38:21Z

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();

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.396245 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO