loading...

re: 3 Ways to Clone Objects in JavaScript VIEW POST

FULL DISCUSSION
 

Also have some issues when clone object with JSON.parse(JSON.stringify)
Can you check?

class Person {
  #name = "";
  constructor(name) {
    this.#name = name;
  }

  greet() {
    console.log("hi, " + this.#name);
  }
}

const p = new Person("Peter");

const obj = { d: new Date(), p };
const newObj = JSON.parse(JSON.stringify(obj));

console.log(typeof obj.d); // output: object
console.log(typeof newObj.d); // output: string

obj.p.greet(); // output: hi, Peter
newObj.p.greet(); // Uncaught TypeError: newObj.p.greet is not a function
 

I should of mentioned...the JSON method won’t be able to clone methods 😣

Check out this article, it has more info:
google.ca/amp/s/scotch.io/bar-talk...

 

Thank you,
And I have some questions about this,
When I copy:

const obj = {n1: 3, n2: new Number(4)};
const newObj = JSON.parse(JSON.stringify(obj));

console.log(typeof obj.n1); // number
console.log(typeof obj.n2); // object

console.log(typeof newObj.n1); // number
console.log(typeof newObj.n2); // number

obj.n2 and newObj.n2 are the same?

And as in my previous comment, when I copy:

const obj = {d: new Date()};
const newObj = JSON.parse(JSON.stringify(obj));

console.log(typeof obj.d); // object
console.log(typeof newObj.d); // string

Another question, when I create an object by Object.create like this:

const obj = Object.create({}, { "p": {readable: false, value: 11 }});
const newObj = JSON.parse(JSON.stringify(obj));

console.log(obj.p); // 11
console.log(newObj.p); // undefined

Why that, we cannot clone it without readable it? Please help me understand, thank you!

code of conduct - report abuse