I have a specific entity class defined as follows:
export class Contact {
id: number;
firstName: string;
lastName: string;
constructor(id?, firstName?, lastName?) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
}
I am now looking to create a separate instance from the Contact class:
export class MyComponent {
contactSrc = new Contact();
contactDest = new Contact();
constructor() {
this.contactSrc.firstName = "Adam"
}
handleCopyOfObject() {
console.log("firstName for contactSrc: " + this.contactSrc.firstName);
this.contactDest = this.contactSrc;
this.contactDest.firstName = "Mohsen";
console.log("-----------result after copy -----------");
console.log("firstName for contactSrc: " + this.contactSrc.firstName);
console.log("firstName for contactDest: " + this.contactDest.firstName);
}
}
When running the code, the output is as follows:
firstName for contactSrc: Adam
-----------result after copy -----------
firstName for contactSrc: Mohsen
firstName for contactDest: Mohsen
The issue is that modifying contactDest.firstName also impacts contactSrc.firstName. How can I update contactDest.firstName without affecting contactSrc.firstName?