Search code examples
javascriptclassinstanceinstanceof

Getting class name of instance and using it to create new instances in JS


I have many instances of different classes, I want to select any of them randomly (say inst1) and create a new instance of the class of selected instance (say cls1). This is how I'm implementing it:

// getting class name of selected instance (say inst1), i.e. clsName is cls1
let clsName = inst1.constructor.name;

// use the class name obtained above to create new instance
let newInst = new clsName();

But it gives me error saying; "Uncaught TypeError: clsName is not a constructor at HTMLDocument."

Is there a way to get around?


Solution

  • claName is a string, not a function. The constructor function is inst1.constructor, call that.

    class Test {
      constructor() {
        console.log("constructing a Test");
      }
    }
    
    inst1 = new Test();
    cls = inst1.constructor;
    inst2 = new cls;