skip to Main Content

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?

(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


  1. Call the constructor directly !

    const aCopy = new (sampleInstance.constructor as any)();
    console.log(aCopy);
    

    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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 1- Get a reference to the constructor function of the existing
    instance using its prototype.

    2- Use the retrieved constructor to create a new instance of the same
    class.

    class sampleClass_A { name = "Archimedes"; }
    class sampleClass_B { name = "Pythagoras"; }
    
    let sampleInstance = new sampleClass_A();
    
    // Step 1: Retrieve the constructor
    const constructor = sampleInstance.__proto__.constructor;
    
    // Step 2: Create a new instance
    let newInstanceOfTheSameClass = new constructor();
    
    console.log(newInstanceOfTheSameClass.name); // "Archimedes"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search