I have an object named uniqueObject
of an unspecified class and I am in need of creating a duplicate object from the same class. Here's my current approach:
- I extract the class name using
uniqueObject.constructor.name
. - Then, I generate a new object of the same class using
.eval(`new ${uniqueObject.constructor.name}()`)
The current code snippet functions without issues:
class classA { name = "Albert";}
class classB { name = "Isaac";}
let uniqueObject = new classA();
// later in the code, the constructor of uniqueObject is unknown
let extractedConstructorName = uniqueObject.constructor.name
let duplicatedObjectOfSameClass = eval(`new ${extractedConstructorName}()`);
console.log(duplicatedObjectOfSameClass .name); // "Albert"
However, I would like to avoid using eval()
. Is there a more elegant solution?
(I am unable to utilize window[extractedConstructorName]
as this code will not be executed in a web browser under normal circumstances. (I am unsure if it would even function in a browser.))