0

Is it possible to declare an object using a string? I have some inherited classes and want to set the object based on a value passed, rather than doing a switch statement like this.

function getObject(properties) {
    switch (properties.objectType) {
          case "object1":
                return new object1();
                break;
          case "object2":
                return new object2();
                break;
     }
}
    

I would rather do something like this

function getObject(properties) {
    return new Object.create(properties.objectType);

    //or
    //return new [properties.objectType](); 
}
StripyTiger
  • 685
  • 10
  • 26
  • Imho looks more like a dupe of [Dynamically loading a typescript class (reflection for typescript)](https://stackoverflow.com/questions/15338610), [Create an instance of a class in ES6 with a dynamic name?](https://stackoverflow.com/questions/34655616), [Create object from class name in JavasScript ECMAScript 6](https://stackoverflow.com/questions/31776949), [Get object class from string name in javascript](https://stackoverflow.com/questions) – Andreas Nov 25 '21 at 13:48

0 Answers0