Generating a fresh instance of a class that mirrors an already existing instance, all without relying on eval()

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:

  1. I extract the class name using uniqueObject.constructor.name.
  2. 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.))

Answer №1

In the case that you are utilizing TypeScript, as demonstrated in this code snippet

class exampleClass_A { name = "Archimedes";}

I have crafted a demonstration for you:

class exampleClass_A { name = "Archimedes";}
class exampleClass_B { name = "Pythagoras";}

let exampleInstance = new exampleClass_A();

// subsequently, in another section of the code, the constructor of exampleInstance becomes unknown
//let constructorName = exampleInstance.constructor.name;
//let newInstanceOfTheSameClass = eval(`new ${constructorName}()`); // how can this be accomplished without eval()???

let newInstanceOfTheSameClass = new exampleInstance.constructor();
console.log(newInstanceOfTheSameClass .name); // "Archimedes"

https://jsfiddle.net/t9gdasur/

Kindly inform me if it is effective. If not, I will attempt an alternative approach.

Answer №2

Directly invoke the constructor!

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

The potential downside is that the constructor is not typed, so you will need to perform a cast and the returned value will lack typing.

Playground

Answer №3

1- Obtain the reference to the constructor function of the current instance by accessing its prototype.

2- Utilize the retrieved constructor to generate a fresh instance of the identical class.

class sampleClass_A { name = "Archimedes"; }
class sampleClass_B { name = "Pythagoras"; }

let sampleInstance = new sampleClass_A();

// Step 1: Obtain the constructor
const constructor = sampleInstance.__proto__.constructor;

// Step 2: Generate a new instance
let newInstanceOfTheSameClass = new constructor();

console.log(newInstanceOfTheSameClass.name); // "Archimedes"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for concealing tick labels in d3 using TypeScript

When trying to hide tick labels by passing an empty string to the .tickFormat("") method, I encountered an issue with Typescript. The error message received was as follows: TS2769: No overload matches this call. Overload 1 of 3, '(format: null): Axi ...

Filtering in JavaScript arrays based on conditions that are not related to the elements in the array

Consider the following code snippet: var numbersArray = [1, 3, 6, 8, 11]; var returnedArray = numbersArray.filter(function(number) { const condition = false // or true sometimes return number > 7 && condition ; }); console.log(returnedArra ...

I need to display the product name associated with the product_id found in the line_items array within the order table. I aim to achieve this functionality by utilizing Laravel with Vue.js

In my database, there is a cell called line_items in the orders table that contains data like: [ {"customer_id":"30","product_id":"10","unit_id":"2","quantity":"1","price":"2700","total_price":"2700"}, {"customer_id":"30","product_id":"43"," ...

Dealing with jQuery hover/toggle state conflicts in Internet Explorer?

Check out my code snippet: <!doctype html> <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <style type="text/css"> label {display:block; w ...

NestJS Resolver Problem: Getting an Undefined Error

Could use a bit of assistance. I'm currently working on a mutation and encountering the following error: ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'entryUser') Here is the resolver code snippet: export class Us ...

Error encountered in ES6 destructuring syntax

Could you please assist me in figuring out what is causing the issue here: var foo = { bar: 1, baz: 2 }; var { bar, baz } = foo; I encountered an error SyntaxError: Unexpected token {. I am using node v5.4.1 and I am unsure if the problem lies wit ...

Error in content policy for CSS in Stripe Checkout

I am currently attempting to integrate Stripe Checkout into my Ionic App. I have created a Directive that injects the form into my content view, however, upon execution, the CSS fails due to a content policy violation: checkout.js:2Refused to load the s ...

Keep a vigilant eye on the peak utilization of memory within the Node.js process

I am in search of a way to effectively monitor the maximum memory usage in a Node.js process, regardless of whether there are memory leaks or not. The processes in question include both real applications and synthetic tests. My expectation is that it sho ...

How can an Angular directive dynamically update template fields with the latest model values from the controller?

I am currently working with a <superhero> directive that includes two other directives: web-buttons, which handles form validation and posting the updated ngModel value to the respective controller. fieldMap, which generates dynamic fields based on ...

Image cannot be shown on HTML webpage

There seems to be an issue with the rendering of the image on the index.html page. All the necessary files, including index.html, app.js, and the image file are located in a virtual machine (VM). After successfully logging in with login.js, the page redire ...

Error message "Angular build with --prod causes Uncaught TypeError: e is not a constructor when running ng serve"

I am encountering an issue while deploying my Angular application to production. The application functions correctly in development and had previously worked on production as well. To build the application, I am using: ng build --prod --base-href="/site/ ...

Utilize JavaScript to substitute font family with a designated class name

After discovering a code snippet that can change font family based on ID, I am interested in implementing it on my website but with a twist - using classes instead of IDs. <!DOCTYPE html> <html> <body> <div class="myP">This is a ...

Import the CSV file and store it in a designated directory using JQuery

My goal is to enable users to upload a CSV file from an HTML page and have it saved to a specified local directory upon upload. Two possible scenarios could unfold: if the uploaded file already exists, it should be overwritten; otherwise, a new file shoul ...

Is there a proper way to supply createContext with a default value object that includes functions?

As I was creating my context, I set an initial state and passed the necessary functions for useContext. Although this method is functional, I'm concerned it may present challenges in larger projects. Does anyone have suggestions for a more efficient a ...

Control and manage AJAX POST requests in the controller

I'm currently working on implementing an ajax post request feature in my project. The goal is to have a button on my html page trigger a javascript event listener, which then initiates an ajax post request to receive some text data. However, I seem to ...

Deleting a li element within an AJAX response function can be accomplished by targeting the specific

I am attempting to remove the li element that is the parent of the clicked a element. Here is the code I am using: function vanish(id_arg){ $.ajax({ url: "/vanish/", type: "POST", data: {id_to_delete: id_arg}, ...

The functionality of loading JSON is not working properly in ePub3

Currently, I am working on a project involving the creation of an ePub3 eBook. One of the exciting features I have successfully integrated is three.js to showcase some models. My next goal is to develop 'hotspot' elements (small cubes that users ...

Preparing data before using Kendo UI upload function is essential

I need to pass a data (specifically a GUID) to the upload method of the kendoUpload, so that a particular MVC Controller action method can receive this data each time the upload occurs. $("#propertyAttachmentUpload").kendoUpload({ async: { ...

Ways to recover information that is not typically found

My firebase database has two main trees: "tag" and "user". Each user is associated with a set of tags, referred to as preferences. Here is the structure of my database: https://i.sstatic.net/m98EO.jpg I am trying to display a list of preferences that a s ...

Instructions on filling the star icon with color upon clicking the button

Currently working on a project using codeIgniter where I have a form for rating products. I am facing an issue where, upon clicking the star button, only the border color changes to yellow while the center of the button remains white. Can someone please g ...