0

I have this object

var person1{
    name :  "John",
    lastName : "Doe"
}

And I did an assignment like this

person2 = person1;

But If I do this:

person1.name = "Mike";

Then person2.name is "Mike"
What I'm trying is to make person2 "independent".
What is going on? is like "referencing objects" ?

1
  • Assigning objects with/to variables is basically referencing them. Also you're missing a equal sign ^_^. Commented Jun 3, 2015 at 23:24

4 Answers 4

2

You're exactly right. It is a referencing situation. There is no cloning going on when you assign an object to a variable, the program just creates a new reference to person1 called person2

You would have to use a dedicated cloning function, depending on if you are using pure JS or a framework like jQuery.

Here is a pure JS solution (source http://heyjavascript.com/4-creative-ways-to-clone-objects/):

function cloneObject(obj) {
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }

    var temp = obj.constructor(); // give temp the original obj's constructor
    for (var key in obj) {
        temp[key] = cloneObject(obj[key]);
    }

    return temp;
}
var person2 = cloneObject(person1);
Sign up to request clarification or add additional context in comments.

1 Comment

Oh very interesting! thanks! I'm trying to understand that code :P !
1

Assuming the object is serializable to JSON, you could do:

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

1 Comment

Nice! very simple and efficient!
1

In that situation I do this:

// a function that returns a generic object
function newPerson(){
return {name:"",lastName:""};

}

//then, calling the function we get an independent object 
var person1=newPerson();
var person2=newPerson();
person1.name="Jon";
person2.name="Bob";

1 Comment

Yes, perhaps is not the 'standard' way, but it looks simpler , you can even add methods
0

You can do this

var p2 ={ name : person1.name, lastname : person1.lastName }

this way, it won't be referenced because you're passing simple types, not objects

Comments

Your Answer

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.