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:
- I look up the class name with
sampleInstance.constructor.name
. - Next, I use
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.))
3
Answers
Call the constructor directly !
The only downside I see is that the constructor is not type, so you’ll have to cast it and the returned value won’t be typed.
Playground
Assuming you’re using typescript, as seen in this instance code
I created a fiddle for you:
https://jsfiddle.net/t9gdasur/
Let me know if it works. if not, I’ll try something else.