1

I have read how to clone objects in javascript and I know how to copy properties from the object. But I not only want to copy object's properties but I also want the copied object to have all the methods as the parent object had and I am not able to figure out how:

Here is what's happening:

var obj = {
    'firstname' : "Harsh",        // <<< Parent object
    'lastnmae'  : "singh",

    introduce() {
        console.log("Hello I am " + this.firstname);
    }
}

var objCopy = JSON.parse(JSON.stringify(obj));   // deep copying the parent object

obj.introduce();  // << works fine when called on the parent object
objCopy.introduce(); // << does not work
                     // but I thought objCopy is the copy of obj ???

EDIT: I don't want shallow copying , I want a deep copy of the object. Most methods that I have come across copy only properties and not functions. I have gone through other articles but haven't found any answers.

Yuseff
  • 169
  • 4
  • 14
  • Functions can't be serialized in JSON. – Barmar Jan 09 '21 at 07:00
  • I don't understand your problem. There are dozens of answers in that question, and most of them don't use JSON. The JSON answers clearly say that they won't work if the object contains functions. – Barmar Jan 09 '21 at 07:03
  • See this [Clone The Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#cloning_an_object) – Ali Malek Jan 09 '21 at 07:33

1 Answers1

0

You can do this working with classes like this:

class  Obj  {
    constructor() {
    this.firstname = "Harsh",
    this.name = 'singh',     

    this.introduce=function() {
        console.log(`Hello I am ${this.firstname}`);
    } 
   }
  }

  var a=new Obj()

  console.log(a.introduce())
liontass
  • 730
  • 9
  • 24