简体   繁体   English

Javascript:object1 = object2究竟产生了什么?

[英]Javascript: object1 = object2 produce what exactly?

If I have 2 type of objects: 如果我有2种类型的对象:

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. 如果我做object1=object2请问在所有级别上object1到底发生了什么。

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. 现在, ab引用相同的对象。 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? 那么{ value: 2, bStuff: true }对象发生了什么? 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. 一旦告诉b引用了一个不同的对象,则没有现有变量对其进行引用,因此最终垃圾收集器将找到它并对其进行处理。


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 ; 现在object1object2的引用, object1任何更改都会更改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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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