简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM