I have an instance sampleInstance
of an unknown class and I need to create a second instance of the same class. Here's what I am doing right now:
sampleInstance.constructor.name
.eval(`new ${sampleInstance.constructor.name}()`)
to create a new instance of the same class.The code below works fine:
class sampleClass_A { name = "Archimedes";}
class sampleClass_B { name = "Pythagoras";}
let sampleInstance = new sampleClass_A();
// later, in another part of the code, I don't know the constructor of sampleInstance anymore
let constructorName = sampleInstance.constructor.name
let newInstanceOfTheSameClass = eval(`new ${constructorName}()`); // how to do without eval()???
console.log(newInstanceOfTheSameClass .name); // "Archimedes"
But I'd rather not use eval()
. What's a cleaner alternative?
(I cannot use window[constructorName]
because this code will not run in a browser in the general case. (Not even sure if it would work in a browser.))
Assuming you're using typescript, as seen in this instance code
class sampleClass_A { name = "Archimedes";}
I created a fiddle for you:
class sampleClass_A { name = "Archimedes";}
class sampleClass_B { name = "Pythagoras";}
let sampleInstance = new sampleClass_A();
// later, in another part of the code, I don't know the constructor of sampleInstance anymore
//let constructorName = sampleInstance.constructor.name;
//let newInstanceOfTheSameClass = eval(`new ${constructorName}()`); // how to do without eval()???
let newInstanceOfTheSameClass = new sampleInstance.constructor();
console.log(newInstanceOfTheSameClass .name); // "Archimedes"
https://jsfiddle.net/t9gdasur/
Let me know if it works. if not, I'll try something else.