DEV Community

Cover image for Object memory reference in JS

Object memory reference in JS

Akbar Ali on March 12, 2024

const person1 = { name: "Alex", address: "Toronto" } const person2 = person1; person2.name = "John"; console.log(person1); Enter ...
Collapse
 
efpage profile image
Eckehard

'JSON.stringify' does not work if you use any memory references in your object:

function test() { console.log("This is a Test") }

const person1 = {
  name: {
    first: "Alex",
    last: "Telles"
  },
  f: test,
  address: "XYZ"
}
person1.f()

const person2 = JSON.parse(JSON.stringify(person1));

person2.f() //Uncaught TypeError TypeError: person2.f is not a function
Enter fullscreen mode Exit fullscreen mode

Intrestingly, f is completely skipped in the output:

JSON.stringify(person1) -> {"name":{"first":"Alex","last":"Telles"},"address":"XYZ"}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pulimoodan profile image
Akbar Ali

Yeah, that's a concern.

So, structuredClone is the only way.

Is there any other workaround?

Collapse
 
pulimoodan profile image
Akbar Ali

I am gonna edit my article with these later