Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating new instance of the same class as an existing instance, without using eval()

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:

  1. I look up the class name with sampleInstance.constructor.name.
  2. 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(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.))

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading