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(); 
}
Rahul Chawla
  • 190
  • 1
  • 3
  • 14
  • Why? I dont know any usecase for this – Jonas Wilms Jan 13 '18 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. `// 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(); } ` – Rahul Chawla Jan 13 '18 at 11:53

3 Answers3

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();
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 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. – Rahul Chawla Jan 14 '18 at 10:16
1

You can try this using window

var className = 'hello'
var obj = new window[className];
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • I am getting this error : `ReferenceError: window is not defined` – Rahul Chawla Jan 13 '18 at 11:29
  • 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: – Sajeetharan Jan 13 '18 at 11:44
  • https://stackoverflow.com/questions/45964178/referenceerror-window-is-not-defined-at-object-anonymous-node-js – Sajeetharan Jan 13 '18 at 11:44
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();
}
pouya
  • 3,400
  • 6
  • 38
  • 53