0

What is the point of deep-cloning a JavaScript object? If you want a copy, why not just declare another variable and set its value to the original object?

Essentially, why would you want to do this:

var person = {name: "Jean", age: 47};
var clone = $(person).clone();

When this seems more simple:

var person1 = {name: "Jean", age: 47};
clone = person1;
asked Mar 6, 2014 at 22:35

2 Answers 2

2

Assignment Case:

var person1 = {name: "Ben", age: 23};
var clone = person1;

When doing an assignment with an object to a new variable, that new variable will contain the reference to the object. In this case, the variable 'clone' will refer to the same object as person1 does. So basically both person1 and clone point to the same object and any changes done to either variable will change the person object they both point to.

Clone Case:

var person = {name: "Ben", age: 23};
var clone = $(person).clone();

Here the object person is cloned and returns a reference to a new object with the same exact properties the person object holds. So, what this means is that both person and clone contain a reference to their own unique object and changes done to one will not affect the other.

answered Mar 6, 2014 at 22:39
1

Because if you don't:

clone.name = "Tom";
console.log(person.name) => "Tom"

IOW, it will be the same object, with a different name.

answered Mar 6, 2014 at 22:37
2
  • So changing person also changes the clone? Commented Mar 6, 2014 at 22:41
  • 1
    Yes, it's just an alias Commented Mar 6, 2014 at 22:42

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.