thednp
thednp

Reputation: 4479

Javascript: object1 = object2 produce what exactly?

If I have 2 type of objects:

object1 : {
    value : { foo1: {}, foo2: 5 }, state: true, etc = {}
}

And

object2 : {
    value : { foo1: { value: 5}, foo2: 6 }, state: true, etc = {}
}

If I do object1=object2 what exactly happens with object1 on all levels please.

Upvotes: 1

Views: 826

Answers (2)

Alex Wayne
Alex Wayne

Reputation: 187134

I'm going to simplify that a bit:

var a = { value: 1, aStuff: true };
var b = { value: 2, bStuff: true };
b = a;
console.log(b); // { value: 1, aStuff: true }

Now a and b reference the same object. Think of it like the same object is accessible by two names. Which means this happens when you change that object:

a.value = 5
console.log(a); // { value: 5, aStuff: true }

Two names, one object.

So what happened to what to the { value: 2, bStuff: true } object? Once you tell b to reference a different object then no existing variable has a reference to it, so eventually the garbage collector will find it and dispose of it.


What happens with inner objects? That is the question..

Nothing at all. The outer object still holds references the values it contains. All that's changed is that you have two variables pointing to that same outer object.

Upvotes: 2

Marcos Casagrande
Marcos Casagrande

Reputation: 40434

object1 is now a reference of object2, any change in object1, will change object2;

var object1 = { foo: 'bar' };

var object2 = {
    value : { foo1: { value: 5}, foo2: 6 }
};

object1 = object2; // the { foo: 'bar' } is gone.

object1.foo2 = 7; //This changes object2.foo2 value
console.log(object2.foo2); //7

Upvotes: 2

Related Questions